【问题标题】:How do I access embedded resources in Visual Studios using Visual C#?如何使用 Visual C# 访问 Visual Studios 中的嵌入式资源?
【发布时间】:2015-07-24 09:32:40
【问题描述】:

我看过很多关于此的其他帖子,但它们毫无意义。这是我在另一篇文章中看到的结构。

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

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

我不明白"MyCompany.MyProduct.MyFile.txt" 部分的内容。是“WindowsFormApplication2.Properties.Resources.LabelData.txt”吗?因为那行不通。我不断收到 NullReferenceException ......我假设它没有正确的文件。这是我的代码。

public void readAllLabelValues()
        {

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

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))

            using (StreamReader Reader = new StreamReader(stream))
            {
                foreach (Label label in tableLayoutPanel1.Controls.OfType<Label>())
                {
                    label.Text = (Reader.ReadLine());
                }
            }
        }

感谢您的帮助。

【问题讨论】:

  • 确保您在文本文件的属性中将构建操作更改为 Embedded Resource 而不是默认的 Content 值。
  • 在VS的解决方案资源管理器中选择文件,然后转到属性窗口并按照上述操作
  • 请标记(并投票)帮助您解决问题的答案。

标签: c# embedded-resource


【解决方案1】:

您可以在 microsoft 站点 (https://support.microsoft.com/en-us/kb/319292) 中看到命名约定为:

编译器将项目的根命名空间添加到 项目中包含的资源。例如,如果 您项目的根命名空间是 MyNamespace,资源被命名 MyNamespace.MyTextFile.txt 和 MyNamespace.MyImage.bmp。

您可以使用调试器通过以下代码找出资源名称是什么:

thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = thisExe.GetManifestResourceNames();

如果您在资源中看不到它,请确保您已在文本文件的属性中将构建操作更改为 Embedded Resource 而不是默认的 Content 值。

【讨论】:

  • 如何将其打印出来以便我可以看到名称?
  • foreach(资源中的变量名) Console.WriteLine(name);
  • 那么是LabelData.LabelData.txt吗?
  • 它应该是 nameSpace 作为前缀,如果您的 nameSpace 是 LabelData,则后跟 .LabelData.txt 是的,但它可能是您的项目名称,它是默认的 nameSpace
【解决方案2】:
WindowsFormApplication2.LabelData.txt

【讨论】:

  • 当我运行告诉我所有命名空间的东西时,我得到了其中一个的 WindowsFormsApplication2.Properties.Resources.resources。它没有抛出空异常,但我如何指定 LabelData.txt 文件?
【解决方案3】:

我发现您可以为此使用 Application.StartUpPath。这是我用来创建有效路径的代码:

string fileLocation = Path.Combine(Application.StartupPath, "programData.txt");

            if (!File.Exists(fileLocation))
            {
                File.Create(fileLocation);
            }

然后要对其进行读写,只需创建指向 fileLocation 的 StreamReader 或 StreamWriter。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-10
    • 2013-11-25
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    相关资源
    最近更新 更多