Question

I created a quick test method to experiment with checking for files and their contents, but for some reason I get the error "not all code paths return a value". As far as I can see, they do, except for the main "if" statement. But if I set a return in that statement it will override the other returns.

Can anyone tell me why this is happening/explain what causes the error?

public static bool FileCheck()
{
    string file = @"C:\Temp\test.txt";
    Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

    if (File.Exists(file) == true)
    {
        StreamReader rdr = new StreamReader(file);
        string myString = rdr.ReadToEnd();

        if (myString == null)
        {
            Console.WriteLine("File empty");
            return false;
        }
        else { Console.WriteLine(myString); return true; }
    }
}
Was it helpful?

Solution 2

there is no else to go along with this if

if (File.Exists(file) == true)  

if it is false, nothing is returned. So you need to add a return false at the end.

if (File.Exists(file) == true)  
{
   ...
}

return false;  

When your method executes it is expected to return the type you defined. In your case when the method is called, it is expected to return a boolean. When the code execution path goes into your if statement, it is fine because it returns a boolean. If the code does NOT go into the if, that your code does not return anything. That is the error. Walk through the code with pencil and paper and see how it executes.

OTHER TIPS

What happens when if (File.Exists(file) == true) is false the compiler does not know because there are no more lines to return a Boolean value. So with that error alerts you.

Adding return boolean; after if the compiler know what to do

if (File.Exists(file) == true)
    {
        StreamReader rdr = new StreamReader(file);
        string myString = rdr.ReadToEnd();

        if (myString == null)
        {
            Console.WriteLine("File empty");
            return false;
        }
        else { Console.WriteLine(myString); return true; }
    }
 return false; ///<=============

It can work with your logical file access

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top