Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何读取嵌入式资源文本文件_.net_Embedded Resource_Streamreader - Fatal编程技术网

.net 如何读取嵌入式资源文本文件

.net 如何读取嵌入式资源文本文件,.net,embedded-resource,streamreader,.net,Embedded Resource,Streamreader,如何使用StreamReader读取嵌入式资源(文本文件)并将其作为字符串返回?我当前的脚本使用Windows窗体和文本框,允许用户查找和替换未嵌入的文本文件中的文本 private void button1_Click(object sender, EventArgs e) { StringCollection strValuesToSearch = new StringCollection(); strValuesToSearch.Add("Apple"); stri

如何使用
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();
}

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

例如,从我发布的页面:

注意:需要使用System.Reflection添加
以使其工作

   Assembly _assembly;
   StreamReader _textStreamReader;

   try
   {
      _assembly = Assembly.GetExecutingAssembly();
      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
   }
   catch
   {
      MessageBox.Show("Error accessing resources!");
   }
您可以使用:

  • 添加以下用法

    using System.IO;
    using System.Reflection;
    
  • 设置相关文件的属性:
    参数
    生成操作
    带值
    嵌入资源

  • 使用以下代码

    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
    是嵌入在
    程序集中的一个资源的名称。
    例如,如果嵌入一个名为
    “MyFile.txt”
    的文本文件,该文件位于默认命名空间为
    “MyCompany.MyProduct”
    的项目根目录中,则
    resourceName
    “MyCompany.MyProduct.MyFile.txt”
    。 可以使用获取程序集中所有资源的列表


  • 只从文件名中获取
    resourceName
    (通过传递名称空间)是一个非常聪明的人:


    一个完整的例子:

    公共字符串读取资源(字符串名称)
    {
    //确定路径
    var assembly=assembly.getExecutionGassembly();
    字符串resourcePath=name;
    //格式:“{Namespace}.{Folder}.{filename}.{Extension}”
    如果(!name.StartsWith(nameof(有效抽屉编译器)))
    {
    resourcePath=assembly.GetManifestResourceNames()
    .Single(str=>str.EndsWith(name));
    }
    使用(Stream=assembly.GetManifestResourceStream(resourcePath))
    使用(StreamReader=新StreamReader(stream))
    {
    返回reader.ReadToEnd();
    }
    }
    
    当您将文件添加到资源中时,应将其访问修饰符选择为public,这样您就可以进行如下操作

    byte[] clistAsByteArray = Properties.Resources.CLIST01;
    
    CLIST01是嵌入文件的名称


    实际上,您可以转到resources.Designer.cs,查看getter的名称。

    您也可以使用@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();
        }
    }
    

    在VisualStudio中,您可以通过项目属性的“资源”选项卡(本例中为“分析”)直接嵌入对文件资源的访问。

    然后,用户可以将生成的文件作为字节数组进行访问

    byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;
    
    如果您需要它作为一个流,那么(从)


    我读取嵌入式资源文本文件使用:

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

    我知道这是一条古老的线索,但这对我来说很有用:

  • 将文本文件添加到项目资源中
  • 将访问修饰符设置为public,如上面Andrew Hill所示
  • 这样读课文:

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

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

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

    访问文件所需的C#代码是不同的,这取决于首先添加文件所使用的方法

    方法1:添加现有文件,将属性设置为
    Embedded Resource
    将文件添加到项目中,然后将类型设置为
    嵌入式资源

    注意:如果使用此方法添加文件,则可以使用
    GetManifestResourceStream
    访问它(请参阅)

    方法2:将文件添加到
    Resources.resx
    打开
    Resources.resx
    文件,使用下拉框添加文件,将
    Access修饰符设置为
    public

    注意:如果使用此方法添加文件,则可以使用
    Properties.Resources
    访问它(请参阅)


    我刚才了解到,文件名中不允许有“.”(点)

    Templates.plainEmailBodyTemplate-en.txt-->有效
    Templates.plainEmailBodyTemplate.en.txt-->无法通过GetManifestResourceStream()工作


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

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

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

    由于NETMF没有
    GetManifestResourceStream

    我很恼火,因为您必须始终在字符串中包含名称空间和文件夹。我想简化对嵌入式资源的访问。这就是我为什么写这个小班的原因。请随意使用和改进

    用法:

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

    public class EmbeddedResources
    {
        private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));
    
        private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));
    
        private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));
    
        private readonly Assembly _assembly;
    
        private readonly string[] _resources;
    
        public EmbeddedResources(Assembly assembly)
        {
            _assembly = assembly;
            _resources = assembly.GetManifestResourceNames();
        }
    
        public static EmbeddedResources CallingResources => _callingResources.Value;
    
        public static EmbeddedResources EntryResources => _entryResources.Value;
    
        public static EmbeddedResources ExecutingResources => _executingResources.Value;
    
        public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));
    
    }
    
    公共类嵌入资源
    {
    private static readonly Lazy _callingResources=new Lazy(()=>new EmbeddedResources(Assembly.GetCallingAssembly());
    private static readonly Lazy _entryResources=new Lazy(()=>new EmbeddedResources(Assembly.GetEntryAssembly());
    private static readonly Lazy _executingResources=new Lazy(()=>new EmbeddedResources(Assembly.getexecutinggassembly());
    专用只读程序集\u程序集;
    私有只读字符串[]\u资源;
    公共嵌入资源(程序集)
    {
    _组装=组装;
    _resources=assembly.GetManifestResourceNames();
    }
    公共静态嵌入资源CallingResources=>\u CallingResources.Value;
    公共静态EmbeddedResources EntryResources=>\u EntryResources.Value;
    公共静态EmbeddedResources ExecutingResources=>\u ExecutingResources.Value;
    公共流GetStream(字符串resName)=>_assembly.GetManifestResourceStream(_resources.Single(s=>s.Contains(resName));
    }
    
    在表单加载事件中读取嵌入的TXT文件。 动态设置变量。 打电话试试看。 为IncludeText()创建Void,Visual Studio会为您执行此操作。单击灯泡以自动生成代码块。 将以下内容放入生成的代码块中

    资源1 资源2 资源3 如果希望将返回的变量发送到其他地方,只需调用另一个函数
    string response = Resources.GetString(Resources.StringResources.MyFileName);
    
    using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
    {
     //...
    }
    
    public class EmbeddedResources
    {
        private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));
    
        private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));
    
        private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));
    
        private readonly Assembly _assembly;
    
        private readonly string[] _resources;
    
        public EmbeddedResources(Assembly assembly)
        {
            _assembly = assembly;
            _resources = assembly.GetManifestResourceNames();
        }
    
        public static EmbeddedResources CallingResources => _callingResources.Value;
    
        public static EmbeddedResources EntryResources => _entryResources.Value;
    
        public static EmbeddedResources ExecutingResources => _executingResources.Value;
    
        public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));
    
    }
    
    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.
    }
    
    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 );
    }
    
    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 );
    }
    
    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream(file3))
    
    using (StreamReader reader = new StreamReader(stream))
    {
        string result3 = reader.ReadToEnd();
        richTextBox1.AppendText(result3);
    }
    
    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);
      }
    
    }
    
    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();
                }
            }
        }
    }
    
        string queryFromResourceFile = Properties.Resources.Testfile.ToString();
    
    // 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 "";      
    }
    
    public class AssemblyTextFileReader
    {
        private readonly Assembly _assembly;
    
        public AssemblyTextFileReader(Assembly assembly)
        {
            _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
        }
    
        public async Task<string> ReadFileAsync(string fileName)
        {
            var resourceName = _assembly.GetManifestResourceName(fileName);
    
            using (var stream = _assembly.GetManifestResourceStream(resourceName))
            {
                using (var reader = new StreamReader(stream))
                {
                    return await reader.ReadToEndAsync();
                }
            }
        }
    }
    
    public static class AssemblyExtensions
    {
        public static string GetManifestResourceName(this Assembly assembly, string fileName)
        {
            string name = assembly.GetManifestResourceNames().SingleOrDefault(n => n.EndsWith(fileName, StringComparison.InvariantCultureIgnoreCase));
    
            if (string.IsNullOrEmpty(name))
            {
                throw new FileNotFoundException($"Embedded file '{fileName}' could not be found in assembly '{assembly.FullName}'.", fileName);
            }
    
            return name;
        }
    }
    
    string textInResourceFile = fileNameSpace.Properties.Resources.fileName;
    
    using System.IO;
    using System.Linq;
    using System.Text;
    
    public static class EmbeddedResourceUtils
    {
        public static string ReadFromResourceFile(string endingFileName)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var manifestResourceNames = assembly.GetManifestResourceNames();
    
            foreach (var resourceName in manifestResourceNames)
            {
                var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
                if (!fileNameFromResourceName.EndsWith(endingFileName))
                {
                    continue;
                }
    
                using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
                {
                    if (manifestResourceStream == null)
                    {
                        continue;
                    }
    
                    using (var streamReader = new StreamReader(manifestResourceStream))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
            }
    
            return null;
        }
        
        // https://stackoverflow.com/a/32176198/3764804
        private static string _GetFileNameFromResourceName(string resourceName)
        {
            var stringBuilder = new StringBuilder();
            var escapeDot = false;
            var haveExtension = false;
    
            for (var resourceNameIndex = resourceName.Length - 1;
                resourceNameIndex >= 0;
                resourceNameIndex--)
            {
                if (resourceName[resourceNameIndex] == '_')
                {
                    escapeDot = true;
                    continue;
                }
    
                if (resourceName[resourceNameIndex] == '.')
                {
                    if (!escapeDot)
                    {
                        if (haveExtension)
                        {
                            stringBuilder.Append('\\');
                            continue;
                        }
    
                        haveExtension = true;
                    }
                }
                else
                {
                    escapeDot = false;
                }
    
                stringBuilder.Append(resourceName[resourceNameIndex]);
            }
    
            var fileName = Path.GetDirectoryName(stringBuilder.ToString());
            return fileName == null ? null : new string(fileName.Reverse().ToArray());
        }
    }
    
    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()
    
    Dim resourceName() As String = ass.GetManifestResourceNames()
    
    Dim sName As String 
        = ass.GetManifestResourceNames()
            .Single(Function(x) x.EndsWith("JavaScript.js"))
    
    Dim sNameList 
        = ass.GetManifestResourceNames()
            .Where(Function(x As String) x.EndsWith(".js"))
    
    using var resStream = assembly.GetManifestResourceStream(GetType(), "file.txt");
    var ms = new MemoryStream();
    await resStream .CopyToAsync(ms);
    var bytes = ms.ToArray();
    
    public class Example
    {
        public static void Main()
        { 
            // Compliant: type of the current class
            Assembly assembly = typeof(Example).Assembly; 
            Console.WriteLine("Assembly name: {0}", assem.FullName);
    
            // Non-compliant
            Assembly assembly = Assembly.GetExecutingAssembly();
            Console.WriteLine("Assembly name: {0}", assem.FullName);
        }
    }