如何读取嵌入资源文本文件

21 浏览
0 Comments

如何读取嵌入资源文本文件

如何使用StreamReader读取嵌入式资源(文本文件)并将其作为字符串返回?我的当前脚本使用Windows表单和文本框,允许用户在非嵌入式文本文件中查找和替换文本。

private void button1_Click(object sender, EventArgs e)
{
    StringCollection strValuesToSearch = new StringCollection();
    strValuesToSearch.Add("Apple");
    string stringToReplace;
    stringToReplace = textBox1.Text;
    StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
    string FileContents;
    FileContents = FileReader.ReadToEnd();
    FileReader.Close();
    foreach (string s in strValuesToSearch)
    {
        if (FileContents.Contains(s))
            FileContents = FileContents.Replace(s, stringToReplace);
    }
    StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
    FileWriter.Write(FileContents);
    FileWriter.Close();
}

admin 更改状态以发布 2023年5月25日
0
0 Comments

您可以使用两种不同的方法将文件添加为资源。

根据第一种方法添加文件的方式不同,访问该文件所需的 C# 代码也不同。

方法1: 添加现有文件,设置属性为嵌入的资源

将文件添加到您的项目中,然后将其类型设置为嵌入的资源

注意:如果您使用此方法添加文件,则可以使用GetManifestResourceStream来访问该文件(请参见@dtb的回答)。

enter image description here

方法2:将文件添加到Resources.resx

打开Resources.resx文件,使用下拉框添加文件,并将访问修饰符设置为public

注意:如果您使用此方法添加文件,则可以使用Properties.Resources来访问它(请参见@Night Walker的回答)。

enter image description here

0
0 Comments

您可以使用Assembly.GetManifestResourceStream方法

  1. 添加以下引用

     using System.IO;
     using System.Reflection;
    

  2. 设置相关文件的属性:
    参数Build Action的值为Embedded Resource

  3. 使用以下代码

     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();
     }
    

    resourceName是嵌入在assembly中的资源之一的名称。
    例如,如果您嵌入了一个名为"MyFile.txt"的文本文件,该文件位于默认命名空间为"MyCompany.MyProduct"的项目的根目录中,则resourceName"MyCompany.MyProduct.MyFile.txt"
    您可以使用Assembly.GetManifestResourceNames方法获取程序集中所有资源的列表。


一个简单的方法来通过文件名获取resourceName(避开命名空间):

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


一个完整的示例:

public string ReadResource(string name)
{
    // Determine path
    var assembly = Assembly.GetExecutingAssembly();
    string resourcePath = name;
    // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
    if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
    {
        resourcePath = assembly.GetManifestResourceNames()
            .Single(str => str.EndsWith(name));
    }
    using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

或者作为一个异步扩展方法:

internal static class AssemblyExtensions
{
    public static async Task ReadResourceAsync(this Assembly assembly, string name)
    {
        // Determine path
        string resourcePath = name;
        // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
        if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
        {
            resourcePath = assembly.GetManifestResourceNames()
                .Single(str => str.EndsWith(name));
        }
        using Stream stream = assembly.GetManifestResourceStream(resourcePath)!;
        using StreamReader reader = new(stream);
        return await reader.ReadToEndAsync();
    }
}
// Usage
string resourceText = await Assembly.GetExecutingAssembly().ReadResourceAsync("myResourceName");

0