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

我关闭

如何使用读取嵌入式资源(文本文件)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();
}
dtb

您可以使用Assembly.GetManifestResourceStream方法

  1. 添加以下用法

    using System.IO;
    using System.Reflection;
    
  2. 设置相关文件的属性:带值的
    参数Build ActionEmbedded 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.GetManifestResourceNamesMethod获得程序集中所有资源的列表


毫不费吹灰之力地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();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章