如何读取嵌入式资源(文本文件)StreamReader并将其作为字符串返回?我当前的脚本使用 Windows 表单和文本框,允许用户在未嵌入的文本文件中查找和替换文本。
StreamReader
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(); }
您可以使用 Assembly.GetManifestResourceStream 方法:
Assembly.GetManifestResourceStream
添加以下用法
using System.IO;
using System.Reflection;
设置相关文件的属性:带值的 参数Build Action``Embedded Resource
Build Action``Embedded Resource
使用以下代码
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 Method获取程序集中所有资源的列表。
resourceName
assembly
"MyFile.txt"
"MyCompany.MyProduct"
"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(); } }