如何阅读嵌入式资源文本文件
如何使用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;
设置相关文件的属性:
带有Embedded Resource值的参数Build Action
使用下面的代码
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方法获取程序集中所有资源的列表。
您可以使用两种单独的方法将文件添加为资源。
访问文件所需的C#代码是不同的,具体取决于首先添加文件的方法。
方法1:添加现有文件,将属性设置为Embedded Resource
将该文件添加到您的项目中,然后将该类型设置为Embedded Resource 。
注意:如果使用此方法添加文件,则可以使用GetManifestResourceStream来访问它(请参阅@dtb的答案)。
方法2:将文件添加到Resources.resx
打开Resources.resx文件,使用下拉框添加文件,将Access Modifier设置为public 。
注意:如果使用此方法添加文件,则可以使用Properties.Resources来访问它(请参阅@Night Walker的答案)。

看看这个页面:http://support.microsoft.com/kb/319292
基本上,您使用System.Reflection来获取对当前Assembly的引用。 然后,您使用GetManifestResourceStream() 。
例如,从我发布的页面:
注意 :需要using System.Reflection;添加using System.Reflection; 为此工作
Assembly _assembly;
StreamReader _textStreamReader;
try
{
_assembly = Assembly.GetExecutingAssembly();
_textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
}
catch
{
MessageBox.Show("Error accessing resources!");
}
链接地址: http://www.djcxy.com/p/23711.html
上一篇: How to read embedded resource text file
下一篇: How to embed multilanguage *.resx (or *.resources) files in single EXE?
