如何使用读取嵌入式资源(文本文件)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();
}
您可以使用Assembly.GetManifestResourceStream
方法:
添加以下用法
using System.IO;
using System.Reflection;
设置相关文件的属性:带值的
参数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
只从文件名获取(通过传递名称空间的东西):
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] 删除。
我来说两句