[英]FileNotFound Exception While Opening File
I have a project that reads several text files into a List via StreamReader, I have the files added to my solution under Resources, when I try to reference the file using StreamReader, I get a "FileNotFound" exception. 我有一个项目,该项目通过StreamReader将多个文本文件读取到列表中,我在“资源”下将文件添加到解决方案中,当我尝试使用StreamReader引用文件时,出现“ FileNotFound”异常。
The files are being copied over to bin\\debug\\Resources, and the error says it's trying to locate them under bin\\debug.. How do I reference them without using the literal path? 文件被复制到bin \\ debug \\ Resources,并且错误表明它正在尝试在bin \\ debug下定位它们。如何在不使用文字路径的情况下引用它们? (eg C:\\users\\etc) since when I compile it won't run on another person's PC if I reference actual path.
(例如C:\\ users \\ etc),因为如果我引用实际路径,则在我编译时它将不会在其他人的PC上运行。
Code that calls text file: 调用文本文件的代码:
using (sr = new StreamReader("FileName.txt"))
{
while (!sr.EndOfStream)
Names.Add(sr.ReadLine());
}
Under the text files properties I have it set to "Copy Always" and under Build Action it's set to "Embedded Resource". 在文本文件属性下,将其设置为“始终复制”,在“生成操作”下将其设置为“嵌入资源”。
Basically my main goal is to compile the project into an exe with the text files being referenced internally (their contents aren't changed by the program), so my application will be portable. 基本上,我的主要目标是使用内部引用的文本文件将项目编译为exe(程序不会更改其内容),因此我的应用程序将是可移植的。
In your situation, the error will be removed by just replacing the path Resources\\FileName.txt
在您的情况下,只需替换路径
Resources\\FileName.txt
,即可消除该错误
In other case, as you mentioned that you want to make a portable .exe. 在其他情况下,正如您提到的,您想制作一个可移植的.exe。 Then you need to embed files in your application.
然后,您需要在应用程序中嵌入文件。 Now see how to embed files in your .exe :
现在查看如何在.exe中嵌入文件:
Properties
in Solution Explorer
Solution Explorer
展开Properties
Double click on Resources
双击
Resources
On left top of Resources
tab, there will be a combo box 在“
Resources
选项卡的左上方,将有一个组合框
Choose Files 选择文件
Embedded in .resx
from Persistence
property. Persistence
属性中选择“ Embedded in .resx
。 To use the file you can use Properties.Resources.YourFile
. 要使用该文件,可以使用
Properties.Resources.YourFile
。
For more details, follow the link http://msdn.microsoft.com/en-us/library/7k989cfy(v=vs.80).aspx 有关更多详细信息,请单击链接http://msdn.microsoft.com/zh-cn/library/7k989cfy(v=vs.80).aspx
Error is clear. 错误很明显。 Change code to:
将代码更改为:
using (sr = new StreamReader("Resources\FileName.txt"))
{
while (!sr.EndOfStream)
Names.Add(sr.ReadLine());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.