Cannot read from a text file - FileNotFound Exception, although file is there

Hey guys,

For some reason, I keep getting a FileNotFound exception while trying to read from a text file, although the path that the StreamReader is looking in is correct - which I know for a fact.

Here is the method that does the reading:

public void setDescription(String file)
{
string currentDir, desc;
try
{
currentDir = Directory.GetCurrentDirectory();
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader(currentDir + "\\" + file);
desc = myFile.ReadToEnd();
myFile.Close();
label11.Text = desc;
}
catch(IOException e)
{
label11.Text = "File read error.\n" + e.Message;
}
}

I have tried this without the current dir and tried reading a file from i.e. C:\file.txt - yet still no success.

Any ideas


Answer this question

Cannot read from a text file - FileNotFound Exception, although file is there

  • Lovenish

    Try using a System.IO.FileInfo object to validate that the file you are expecting to open exists. When in debug mode, have a look at the instance of the (FileInfo) object's FullName property, and ensure that you don't have any problems such as extra spaces in the wrong place, or double sets of backslash characters. You can use the instance's .Exists property to determine whether to continue your operation, too. You may even consider using a FileInfo object as your input parameter.


  • Andreas Öhlund

    Have you checked in the debugger that the path is right Because, if it says file not found, then the file plain is not there.



  • ISV Buddy Team

    You can first determ if the file exists:


    public void setDescription(String file)
    {
    string currentDir = Directory.GetCurrentDirectory();
    string desc = null;

    try
    {
    string fullname = Path.Combine( currentDir, file );

    if( !File.Exists( fullname ) )
    {
    label11.Text = string.Format( "File '{0}' couldn't be found.", fullname );
    }

    // Read the file as one string.
    using( StreamReader myFile = new System.IO.StreamReader( fullname ) )
    {
    desc = myFile.ReadToEnd();
    myFile.Close();
    label11.Text = desc;
    }
    }
    catch(IOException e)
    {
    label11.Text = "File read error.\n" + e.Message;
    }
    }




  • Cannot read from a text file - FileNotFound Exception, although file is there