简体   繁体   中英

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 .

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.

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.

您可以使用Process Monitor (FileMon的后继)来确切地找到应用程序尝试读取的文件。

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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM