简体   繁体   English

C#从资源而不是本地错误中读取文本文件,添加名称空间无效

[英]C# Read text file from resources rather than locally error, adding namespace didnt work

I have tried multiple solutions on here but non of them I can get to work. 我在这里尝试了多种解决方案,但没有一个可以上班。 All i want to do is read a text file from my resources folder rather than the actual local folder. 我要做的就是从我的资源文件夹而不是实际的本地文件夹中读取文本文件。

File name: TextFile.txt 文件名: TextFile.txt

Set to embedded resource. 设置为嵌入式资源。

"Local File" Code that works: 起作用的“本地文件”代码:

string[] spaces = File.ReadAllLines("C:\\Users\\a\\source\\repos\\a\\bin\\Debug\\TextFile.txt");

Current Code: 当前代码:

        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "TextFile.txt";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            string result = reader.ReadToEnd(); 
        }

        string[] spaces = File.ReadAllLines(resourceName);

But I am getting the following error: 但是我收到以下错误:

System.ArgumentNullException: 'Value cannot be null. System.ArgumentNullException:'值不能为null。 Parameter name: stream' 参数名称:stream'

On this line: 在这行上:

using (StreamReader reader = new StreamReader(stream))

EDIT1 Tried this as per link ( Why does GetManifestResourceStream returns null while the resource name exists when calling GetManifestResourceNames? ) and this NULL ERROR : EDIT1按链接尝试了此操作( 为什么在调用GetManifestResourceNames时资源名称存在时GetManifestResourceStream返回null? )和此NULL错误

        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "programname.TextFile.txt";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            string result = reader.ReadToEnd(); 
        }

        string[] spaces = File.ReadAllLines(resourceName);

Same error, am I putting the namespace bit in the wrong place? 同样的错误,我是否将名称空间放在错误的位置?

Edit 2, tried this: 编辑2,尝试了此操作:

        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "programname.Resources.TextFile.txt";
        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            string result = reader.ReadToEnd(); 
        }

        string[] spaces = File.ReadAllLines(resourceName);

New error: 新错误:

System.IO.FileNotFoundException: 'Could not find file 'C:\\Users\\a\\source\\repos\\a\\bin\\Debug\\programname.Resources.TextFile.txt'.' System.IO.FileNotFoundException:'找不到文件'C:\\ Users \\ a \\ source \\ repos \\ a \\ bin \\ Debug \\ programname.Resources.TextFile.txt'。

Location of TextFile.txt TextFile.txt位置

programname
    Resources
        TextFile.txt 

This function will return the correct resource name for your file: 此函数将为您的文件返回正确的资源名称:

string resourceName = assembly.GetManifestResourceNames()
  .Single(str => str.EndsWith("TextFile.txt"));

2nd issue: 第二期:

For string[] spaces = File.ReadAllLines(resourceName); 对于string[] spaces = File.ReadAllLines(resourceName); You can't use the same resourceName (embedded resource). 您不能使用相同的resourceName(嵌入式资源)。 If you need to read text line by line use for example: 如果您需要逐行阅读文本,请使用例如:

using (StreamReader reader = new StreamReader(stream))
{
   while (reader.Peek() >= 0)
   {
      Console.WriteLine(reader.ReadLine());
   }
}

Got this to work by opening Resources.resx , Setting Access Modifier to Public Then adding the file in there. 通过打开Resources.resx ,将Access Modifier设置为Public然后在其中添加文件,使其工作。

Then replaced: 然后更换:

string[] spaces = File.ReadAllLines("C:\\Users\\a\\source\\repos\\a\\bin\\Debug\\TextFile.txt")

With: 带有:

var resourceText = Properties.Resources.TextFile;
var Lines= resourceText.Replace("\r", "").Split('\n');

A little background: 一点背景:

MSDN : MSDN

If you add a resource to your project in the normal way, it will automatically provide a typesafe wrapper for that resource. 如果以正常方式将资源添加到项目中,它将自动为该资源提供类型安全的包装。

For example, in the Solution Explorer, expand the "Properties" node and double click the "Resources.resx" entry. 例如,在解决方案资源管理器中,展开“属性”节点,然后双击“ Resources.resx”条目。 Then add an image via the "Add Resource" button. 然后通过“添加资源”按钮添加图像。 Give that resource a name, say "MyImage". 给该资源起一个名字,说“ MyImage”。

You will then be able to programmatically access that image via "Properties.Resources.MyImage" 然后,您将可以通过“ Properties.Resources.MyImage”以编程方式访问该图像

  • This is the simple and recommended way; 这是简单且推荐的方法; it will let you edit the name in the resource file and will check while coding that the name is correct. 它可以让您编辑资源文件中的名称,并在编码时检查名称是否正确。

Note that the names are stripped of the extension and, as other c# names, are case-sensitive! 请注意,名称已去除扩展名,并且与其他c#名称一样,区分大小写!

  • The other way doesn't register the resources with the .resx file but only add them to the resource folder and marks them as embedded. 另一种方法是不向.resx文件注册资源,而仅将它们添加到资源文件夹中并将其标记为嵌入式。

To use them you can't use a code as simple as the one above. 要使用它们,您不能使用上面的代码那么简单。 Instead you need to find out the name (Intellisense will not help you there) and them use calls to the Reflection namespace. 取而代之的是,您需要找出名称(Intellisense帮不上忙),并且它们使用对Reflection名称空间的调用。

Note that here the names are __not_- stripped of the extension but still are case-sensitive! 请注意,这里的名称是扩展名的__not_-, 但仍然区分大小写!

Example: 例:

If we don't know the exact name we can search in the assembly: 如果我们不知道确切的名称,可以在程序集中搜索:

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var ress = assembly.GetManifestResourceNames()
                   .Where(x => x.Contains(somepattern)).First();

Usually the 1st way is much recommended. 通常,强烈建议使用第一种方法。 Typesafety and Intellisense support alone are well worth mainainting the resx file! 仅类型安全性和Intellisense支持非常值得维护resx文件! Now we can open a stream to read the resource: 现在我们可以打开一个流以读取资源:

List<string> results = new List<string>(); ;
using (Stream stream = assembly.GetManifestResourceStream(ress))
using (StreamReader reader = new StreamReader(stream))
{
    while (reader.Peek()>=0) results.Add(reader.ReadLine());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM