C# 如何从解决方案项中添加的 .txt 文件中读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13317579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:11:21  来源:igfitidea点击:

How do I read from a .txt file added in solution items

c#file-io

提问by NewbornNerd

I've added a dictionary.txt file to my solution items and I want to be reading from that file, not from where it exists on my hard drive, so that if someone else opens my project on their computer they will still be able to read from that file.

我在我的解决方案项中添加了一个 dictionary.txt 文件,我想从该文件中读取,而不是从它存在于我硬盘上的位置读取,这样如果其他人在他们的计算机上打开我的项目,他们仍然能够从该文件中读取。

In another question on there they say to go into properties and change the Copy to Output Directory settings, but I don't see that under my .txt file properties (I'm using VS2010): Read a text file from local folder

在那里的另一个问题中,他们说要进入属性并更改复制到输出目录设置,但我在我的 .txt 文件属性下看不到这一点(我使用的是 VS2010):从本地文件夹读取文本文件

Currently my code reads like this:

目前我的代码是这样的:

string[] dictionary = System.IO.File.ReadAllLines(@"dictionary.txt");

Is there something I need to do or some other way I need to reference the file to make sure it's only referencing the file I've added to the project? Or am I missing something more fundamental?

有什么我需要做的事情还是我需要以其他方式引用文件以确保它只引用我添加到项目中的文件?还是我错过了更基本的东西?

Thanks!

谢谢!

采纳答案by Frank van Puffelen

I assume you've already added the file to your solution and that it shows up in the Solution Explorer in Visual Studio as an item directly under the project you are compiling.

我假设您已经将该文件添加到您的解决方案中,并且它在 Visual Studio 的解决方案资源管理器中显示为您正在编译的项目正下方的一个项目。

  1. Select the text file in the Solution Explorer.
  2. In the Properties panel, set the Build Actionproperty to Embedded Resource
  1. 在解决方案资源管理器中选择文本文件。
  2. 在“属性”面板中,将Build Action属性设置为Embedded Resource

The "Copy to Output Directory setting" just ensures that the file is copied into the Build\Debugor Build\Releasefolder.

“复制到输出目录设置”只是确保将文件复制到Build\DebugBuild\Release文件夹中。

The Embedded Resources action ensures that the files gets bundled into your .exe or .dll file and this is available to your program to load.

嵌入资源操作可确保文件被捆绑到您的 .exe 或 .dll 文件中,并且您的程序可以加载这些文件。