关于C#:从资源读取文件

Reading a file from resources

我已经将sample.txt(它仅包含一行" aaaa")文件嵌入到项目资源中,如此答案。
当我尝试像这样阅读时:

1
string s = File.ReadAllText(global::ConsoleApplication.Properties.Resources.sample);

我收到System.IO.FileNotFoundException'异常。
附加信息:找不到文件'd: Work Projects MyTests ConsoleApplication ConsoleApplication bin Debug aaaa'。

因此,似乎它正在尝试从我的资源文件中获取文件名,而不是读取该文件。 为什么会这样呢? 以及如何使它读取sample.txt

尝试@Ryios的解决方案并获取Argument null异常

1
2
3
4
5
  using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication.Resources.sample.txt"))
        {
            TextReader tr = new StreamReader(stream);
            string fileContents = tr.ReadToEnd();
        }

该文件位于d: Work Projects MyTests ConsoleApplication ConsoleApplication resources sample.txt

ps。 解决了。 我必须设置"构建操作"-将资源嵌入到sample.txt属性中


您无法使用File.ReadAllText读取资源文件。

相反,您需要使用Assembly.GetManifestResourceStream打开资源流。

您也不会传递路径,而是传递名称空间。该文件的名称空间将是"程序集默认名称空间" +该文件所在项目中的文件夹高度+该文件的名称。

想象一下这种结构

  • 专案(xyz.project)
    • 资料夹1
      • 资料夹2
        • SomeFile.Txt

因此,文件的名称空间将是:

xyz.project.Folder1.Folder2.SomeFile.Txt

然后你会这样阅读

1
2
3
4
5
        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
        {
            TextReader tr = new StreamReader(stream);
            string fileContents = tr.ReadToEnd();
        }


您好,建议的解决方案不起作用

返回null

1
Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt")

另一种方法是使用Ressource Data中的MemoryStream

1
2
3
  byte[] aa = Properties.Resources.YOURRESSOURCENAME;
  MemoryStream MS =new MemoryStream(aa);
  StreamReader sr = new StreamReader(MS);

不理想,但可以