在C#中打开文件的问题
我在下面的代码中做错了什么?
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;
}
我将一个 text.txt
文件放入 bin\Debug
文件夹中,出于某种原因,每次输入此文件名 ("text.txt"< /code>) 我收到
System.IO.FileNotFoundException
异常。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设当前工作目录与二进制文件所在的目录相同是不安全的。您通常可以使用如下代码来引用应用程序的目录:
这可能是也可能不是您给定问题的解决方案。顺便说一句,
text
并不是真正合适的文件名变量名。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:
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.如果我想打开始终位于相对于应用程序启动路径的文件夹中的文件,我可以使用:
简单地获取启动路径,然后附加路径的其余部分(子文件夹和/或文件名)。
附带说明:在现实生活中(即在最终用户的配置中),您需要读取的文件的位置很少与应用程序启动路径相关。应用程序通常安装在 Program Files 文件夹中,应用程序数据存储在其他地方。
If I want to open a file that is always in a folder relative to the application's startup path, I use:
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.
File.ReadAllText(path) 与您的代码执行相同的操作。我建议使用像“c:......\text.txt”这样的根路径而不是相对路径。当前目录不一定设置为应用程序的主目录。
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 的后继者)来了解到底发生了什么文件您的应用程序尝试读取。
You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.
我的建议:
或者甚至
您也可以检查文件是否存在:
最后 - 也许您的 text.txt 文件已被其他进程打开,目前无法读取。
My suggestions:
or even
You can also check is file exists:
At last - maybe your text.txt file is open by other process and it can't be read at this moment.