如何阅读embedded式资源文本文件

如何使用StreamReader读取embedded资源(文本文件)并将其作为string返回? 我当前的脚本使用Windows窗体和文本框,允许用户查找并replace未embedded文本文件中的文本。

 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方法 :

  1. 使用添加以下内容

     using System.Reflection; 
  2. 设置相关文件的属性:
    带有Embedded Resource参数Build Action

  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(); } 

resourceNameassembly集中embedded的其中一个resourceName的名称。 例如,如果您embedded名为"MyFile.txt"的文本文件,该文件位于具有默认名称空间"MyCompany.MyProduct"的项目的根目录中,则resourceName"MyCompany.MyProduct.MyFile.txt" 。 您可以使用Assembly.GetManifestResourceNames方法获取程序集中的所有资源的列表。

您可以使用两种不同的方法将文件添加为资源。

访问文件所需的C#代码是不同的 ,具体取决于用于添加文件的方法。

方法1:添加现有文件,将属性设置为Embedded Resource

将文件添加到您的项目,然后将types设置为Embedded Resource

注意:如果使用此方法添加文件,则可以使用GetManifestResourceStream来访问它(请参阅@dtb的答案)。

在这里输入图像描述

方法2:将文件添加到Resources.resx

打开Resources.resx文件,使用下拉框添加文件,将Access Modifier设置为public

注意:如果使用此方法添加文件,则可以使用Properties.Resources来访问它(请参阅@Night Walker的答案)。

在这里输入图像描述

看看这个网页: http : //support.microsoft.com/kb/319292

基本上,您使用System.Reflection来获取当前程序集的引用。 然后,您使用GetManifestResourceStream()

例如,从我张贴的页面:

注意 :需要添加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!"); } 

在Visual Studio中,您可以通过项目属性的资源选项卡(本例中的“分析”)直接embedded对文件资源的访问。 视觉工作室屏幕截图 - 资源标签

生成的文件可以被作为一个字节数组来访问

 byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter; 

如果你需要它作为一个stream,然后(从https://stackoverflow.com/a/4736185/432976

 Stream stream = new MemoryStream(jsonSecrets) 

当您将文件添加到资源时,应该select其访问修饰符为公共状态,而不是您可以进行如下操作。

 byte[] clistAsByteArray = Properties.Resources.CLIST01; 

CLIST01是embedded文件的名称。

其实你可以去resources.Designer.cs看看什么是getter的名字。

我知道这是一个古老的线程,但这是对我有用:

  1. 将文本文件添加到项目资源
  2. 将访问修饰符设置为public,如Andrew Hill所示
  3. 阅读这样的文字:

     textBox1 = new TextBox(); textBox1.Text = Properties.Resources.SomeText; 

我添加到资源的文本:“SomeText.txt”

你也可以使用@ dtb的这个简化版本的答案:

 public string GetEmbeddedResource(string ns, string res) { using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, res)))) { return reader.ReadToEnd(); } } 

我读了一个embedded式资源文本文件使用:

  /// <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); }); 

我刚刚学到的东西是你的文件不允许有一个“。” (点)在文件名。

一个 ”。”在文件名是不好的。

Templates.plainEmailBodyTemplate-en.txt – >工程!
Templates.plainEmailBodyTemplate.en.txt – >不能通过GetManifestResourceStream()工作

可能是因为该框架混淆名称空间与文件名…

我知道这是旧的,但我只是想指出NETMF (.Net MicroFramework),你可以很容易地做到这一点:

 string response = Resources.GetString(Resources.StringResources.MyFileName); 

由于NETMF没有GetManifestResourceStream

通过你所有的能力,我使用这个辅助类以通用的方式从任何程序集和任何名字空间读取资源。

 public class ResourceReader { public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return GetEmbededResourceNames<TAssembly>() .Where(predicate) .Select(name => ReadEmbededResource(typeof(TAssembly), name)) .Where(x => !string.IsNullOrEmpty(x)); } public static IEnumerable<string> GetEmbededResourceNames<TAssembly>() { var assembly = Assembly.GetAssembly(typeof(TAssembly)); return assembly.GetManifestResourceNames(); } public static string ReadEmbededResource<TAssembly, TNamespace>(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name); } public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name) { if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType)); if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}"); } public static string ReadEmbededResource(Type assemblyType, string name) { if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); var assembly = Assembly.GetAssembly(assemblyType); using (var resourceStream = assembly.GetManifestResourceStream(name)) { if (resourceStream == null) return null; using (var streamReader = new StreamReader(resourceStream)) { return streamReader.ReadToEnd(); } } } } 

添加例如Testfile.sql项目菜单 – >属性 – >资源 – >添加现有文件

  string queryFromResourceFile = Properties.Resources.Testfile.ToString(); 

我很烦恼,你必须总是包括在string中的命名空间和文件夹。 我想简化对embedded式资源的访问。 这就是我写这个小class的原因。 随意使用和改进!

用法:

 using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt")) { //... } 

类:

 public class EmbeddedResources { public static EmbeddedResources callingResources; public static EmbeddedResources entryResources; public static EmbeddedResources executingResources; private Assembly assembly; private string[] resources; public static EmbeddedResources CallingResources { get { if (callingResources == null) { callingResources = new EmbeddedResources(Assembly.GetCallingAssembly()); } return callingResources; } } public static EmbeddedResources EntryResources { get { if (entryResources == null) { entryResources = new EmbeddedResources(Assembly.GetEntryAssembly()); } return entryResources; } } public static EmbeddedResources ExecutingResources { get { if (executingResources == null) { executingResources = new EmbeddedResources(Assembly.GetExecutingAssembly()); } return executingResources; } } public EmbeddedResources(Assembly assembly) { this.assembly = assembly; resources = assembly.GetManifestResourceNames(); } public Stream GetStream(string resName) { string[] possibleCandidates = resources.Where(s => s.Contains(resName)).ToArray(); if (possibleCandidates.Length == 0) { return null; } else if (possibleCandidates.Length == 1) { return assembly.GetManifestResourceStream(possibleCandidates[0]); } else { throw new ArgumentException("Ambiguous name, cannot identify resource", "resName"); } } } 

在表单加载事件中读取embedded的TXT文件。

dynamic设置variables。

 string f1 = "AppName.File1.Ext"; string f2 = "AppName.File2.Ext"; string f3 = "AppName.File3.Ext"; 

呼叫试试看。

 try { IncludeText(f1,f2,f3); /// Pass the Resources Dynamically /// through the call stack. } catch (Exception Ex) { MessageBox.Show(Ex.Message); /// Error for if the Stream is Null. } 

为IncludeText()创buildVoid,Visual Studio为你做这个。 单击“灯泡”以自动生成“代码块”。

在生成的代码块中放入以下内容

资源1

 var assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(file1)) using (StreamReader reader = new StreamReader(stream)) { string result1 = reader.ReadToEnd(); richTextBox1.AppendText(result1 + Environment.NewLine + Environment.NewLine ); } 

资源2

 var assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(file2)) using (StreamReader reader = new StreamReader(stream)) { string result2 = reader.ReadToEnd(); richTextBox1.AppendText( result2 + Environment.NewLine + Environment.NewLine ); } 

资源3

 var assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(file3)) using (StreamReader reader = new StreamReader(stream)) { string result3 = reader.ReadToEnd(); richTextBox1.AppendText(result3); } 

如果你想在其他地方发送返回的variables,只需调用另一个函数,然后…

 using (StreamReader reader = new StreamReader(stream)) { string result3 = reader.ReadToEnd(); ///richTextBox1.AppendText(result3); string extVar = result3; /// another try catch here. try { SendVariableToLocation(extVar) { //// Put Code Here. } } catch (Exception ex) { Messagebox.Show(ex.Message); } } 

这实现了这一点,这是一个方法来结合多个txt文件,并阅读他们的embedded式数据,在一个丰富的文本框。 这是我对这个代码示例所期望的效果。

读完这里发布的所有解决scheme后。 这是我解决它的方法:

 // How to embedded a "Text file" inside of a C# project // and read it as a resource from c# code: // // (1) Add Text File to Project. example: 'myfile.txt' // // (2) Change Text File Properties: // Build-action: EmbeddedResource // Logical-name: myfile.txt // (note only 1 dot permitted in filename) // // (3) from c# get the string for the entire embedded file as follows: // // string myfile = GetEmbeddedResourceFile("myfile.txt"); public static string GetEmbeddedResourceFile(string filename) { var a = System.Reflection.Assembly.GetExecutingAssembly(); using (var s = a.GetManifestResourceStream(filename)) using (var r = new System.IO.StreamReader(s)) { string result = r.ReadToEnd(); return result; } return ""; }