C#中我使用的StreamReader读取里面的资源文本文件时得到一个FileNotFound异常文本文件、异常、里面、资源

2023-09-03 08:19:49 作者:入她城、占她心

using (SteamReader sr = new StreamReader("text.txt"))

我也试着不把对的.resx 文件中的文本文件。

I also tried to don't put the text file on the .resx file.

推荐答案

这是您正在使用的的StreamReader 构造函数需要将文件存在磁盘上。如果文件嵌入你的组件内,你可以使用 GetManifestResourceStream 的方法。

The StreamReader constructor that you are using expects the file to exist on the disk. If the file is embedded inside your assembly you could use the GetManifestResourceStream method.

例如:

// Get the current assembly. If the file is embedded inside a different
// assembly you will need to get that assembly
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("AssemblyName.test.txt"))
using (var sr = new StreamReader(stream))
{
    ...
}

根据该资源嵌入到您的程序集将取决于哪里是坐落在层次结构中的文件中的关键。它总是prefixed与装配名称,然后任何可能的子文件夹,如果你有一些。

The key under which the resource is embedded into your assembly will depend on where is the file situated in the hierarchy. It is always prefixed with the assembly name and then any possible subfolders if you have some.

请确保生成操作设置为嵌入的资源在其属性文件。而这里的 文章 有关详细信息访问嵌入的资源。

Make sure that the Build Action is set to Embedded Resource for this file in its properties. And here's an article with more details about accessing embedded resources.