Nadav
Nadav

Reputation: 2717

problem with opening a file in C#

What am I doing wrong in the following code?

public string ReadFromFile(string text)
    {
        string toReturn = "";
        System.IO.FileStream stream = new System.IO.FileStream(text, System.IO.FileMode.Open);
        System.IO.StreamReader reader = new System.IO.StreamReader(text);
        toReturn = reader.ReadToEnd();
        stream.Close();
        return toReturn;
    }

I put a text.txt file inside my bin\Debug folder and for some reason, each time when I enter this file name ("text.txt") I am getting an exception of System.IO.FileNotFoundException.

Upvotes: 0

Views: 3048

Answers (5)

Bart Gijssens
Bart Gijssens

Reputation: 1612

If I want to open a file that is always in a folder relative to the application's startup path, I use:

 Application.StartupPath

to simply get the startuppath, then I append the rest of the path (subfolders and or file name).

On a side note: in real life (i.e. in the end user's configuration) the location of a file you need to read is seldom relative to the applications startup path. Applications are usually installed in the Program Files folder, application data is stored elsewhere.

Upvotes: 1

Przemysław Michalski
Przemysław Michalski

Reputation: 9847

My suggestions:

public string ReadFromFile(string fileName)
        {
            using(System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
            using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
            {
               return = reader.ReadToEnd();
            }
        }

or even

string text = File.OpenText(fileName).ReadToEnd();

You can also check is file exists:

if(File.Exists(fileName)) 
{
   // do something...
}

At last - maybe your text.txt file is open by other process and it can't be read at this moment.

Upvotes: 0

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.

Upvotes: 0

user166010
user166010

Reputation:

File.ReadAllText(path) does the same thing as your code. I would suggest using rooted path like "c:......\text.txt" instead of the relative path. The current directory is not necessarily set to your app's home directory.

Upvotes: 0

Jim Brissom
Jim Brissom

Reputation: 32919

It is not safe to assume that the current working directory is identical to the directory in which your binary is residing. You can usually use code like the following to refer to the directory of your application:

string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string filename = System.IO.Path.Combine(applicationDirectory, text);

This may or may not be a solution for your given problem. On a sidenote, text is not really a decent variable name for a filename.

Upvotes: 4

Related Questions