How to read embedded resource text file

前端 未结 22 2368
悲&欢浪女
悲&欢浪女 2020-11-21 06:03

How do I read an embedded resource (text file) using StreamReader and return it as a string? My current script uses a Windows form and textbox that allows the

相关标签:
22条回答
  • 2020-11-21 06:40

    I wanted to read the embedded resource just as a byte array (without assuming any specific encoding), and I ended up using a MemoryStream which makes it very simple:

    using var resStream = assembly.GetManifestResourceStream(GetType(), "file.txt");
    var ms = new MemoryStream();
    await resStream .CopyToAsync(ms);
    var bytes = ms.ToArray();
    
    0 讨论(0)
  • 2020-11-21 06:41

    You can use the Assembly.GetManifestResourceStream Method:

    1. Add the following usings

      using System.IO;
      using System.Reflection;
      
    2. Set property of relevant file:
      Parameter Build Action with value Embedded Resource

    3. Use the following code

      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 is the name of one of the resources embedded in assembly. For example, if you embed a text file named "MyFile.txt" that is placed in the root of a project with default namespace "MyCompany.MyProduct", then resourceName is "MyCompany.MyProduct.MyFile.txt". You can get a list of all resources in an assembly using the Assembly.GetManifestResourceNames Method.


    A no brainer astute to get the resourceName from the file name only (by pass the namespace stuff):

    string resourceName = assembly.GetManifestResourceNames()
      .Single(str => str.EndsWith("YourFileName.txt"));
    

    A complete example:

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:43

    By all your powers combined I use this helper class for reading resources from any assembly and any namespace in a generic way.

    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();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:45

    After reading all the solutions posted here. This is how I solved it:

    // 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 "";      
    }
    
    0 讨论(0)
  • 2020-11-21 06:49

    Some VS .NET project types don’t auto-generate a .NET (.resx) file. The following steps add a Resource file to your project:

    1. Right-click the project node and select Add/New Item, scroll to Resources File. In the Name box choose an appropriate name, for instance Resources and click the button Add.
    2. The resource file Resources.resx is added to the project and can be seen as a node in the solution explorer.
    3. Actually, two files are created, there is also an auto-generated C# class Resources.Designer.cs. Don’t edit it, it is maintained by VS. The file contains a class named Resources.

    Now you can add a text file as a resource, for example an xml file:

    1. Double-click Resources.resx. Select Add Resource > Add Existing File and scroll to the file you want to be included. Leave the default value Internal for Access Modify.
    2. An icon represents the new resource item. If selected, the property pane shows its properties. For xml files, under the property Encoding select Unicode (UTF-8) – Codepage 65001 instead of the default local codepage. For other text files select the correct encoding of this file, for example codepage 1252.
    3. For text files like xml files, the class Resources has a property of type string that is named after the included file. If the file name is e.g. RibbonManifest.xml, then the property should have the name RibbonManifest. You find the exact name in the code file Resources.Designer.cs.
    4. Use the string property like any other string property, for example: string xml = Resources.RibbonManifest. The general form is ResourceFileName.IncludedTextFileName. Don’t use ResourceManager.GetString since the get-function of the string property has done that already.
    0 讨论(0)
  • 2020-11-21 06:51

    adding e.g. Testfile.sql Project Menu -> Properties -> Resources -> Add Existing file

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

    0 讨论(0)
提交回复
热议问题