如何使用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();
}
对于使用VB.Net的用户
Imports System.IO
Imports System.Reflection
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js"
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
其中MyApplicationName是应用程序的命名空间。它不是程序集名称。此名称在项目的财产(应用程序选项卡)中定义。
如果找不到正确的资源名称,可以使用GetManifestResourceNames()函数
Dim resourceName() As String = ass.GetManifestResourceNames()
or
Dim sName As String
= ass.GetManifestResourceNames()
.Single(Function(x) x.EndsWith("JavaScript.js"))
or
Dim sNameList
= ass.GetManifestResourceNames()
.Where(Function(x As String) x.EndsWith(".js"))
对于使用VB.Net的用户
Imports System.IO
Imports System.Reflection
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js"
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
其中MyApplicationName是应用程序的命名空间。它不是程序集名称。此名称在项目的财产(应用程序选项卡)中定义。
如果找不到正确的资源名称,可以使用GetManifestResourceNames()函数
Dim resourceName() As String = ass.GetManifestResourceNames()
or
Dim sName As String
= ass.GetManifestResourceNames()
.Single(Function(x) x.EndsWith("JavaScript.js"))
or
Dim sNameList
= ass.GetManifestResourceNames()
.Where(Function(x As String) x.EndsWith(".js"))
我读取了一个嵌入式资源文本文件,使用:
/// <summary>
/// Converts to generic list a byte array
/// </summary>
/// <param name="content">byte array (embedded resource)</param>
/// <returns>generic list of strings</returns>
private List<string> GetLines(byte[] content)
{
string s = Encoding.Default.GetString(content, 0, content.Length - 1);
return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
}
示例:
var template = GetLines(Properties.Resources.LasTemplate /* resource name */);
template.ForEach(ln =>
{
Debug.WriteLine(ln);
});