从资源中读取文件

问题描述 投票:3回答:2

我已将sample.txt(它只包含一行“aaaa”)文件嵌入到项目的资源中,就像在这个answer中一样。当我试图像这样读它:

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异常

  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

附:解决了。我必须在sample.txt属性中设置Build Action - embed资源

c# embedded-resource
2个回答
9
投票

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

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

你也没有传递它的路径,你传递它一个命名空间。该文件的命名空间将是程序集默认命名空间+文件所在项目中的文件夹heieracy +文件名。

想象一下这个结构

  • 项目(xyz.project)
  • 文件夹1
  • 文件夹2
  • SomeFile.Txt

所以文件的命名空间将是:

xyz.project.Folder1.Folder2.SomeFile.Txt

然后你会这样读

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

3
投票

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

这回归null

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

另一种方法是使用来自MemoryStreamRessource Data

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

不理想,但它的工作原理

© www.soinside.com 2019 - 2024. All rights reserved.