How to read embedded resource text file

前端 未结 22 2379
悲&欢浪女
悲&欢浪女 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:39

    I was annoyed that you had to always include the namespace and the folder in the string. I wanted to simplify the access to the embedded resources. This is why I wrote this little class. Feel free to use and improve!

    Usage:

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

    Class:

    public class EmbeddedResources
    {
        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.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)));
    
    }
    

提交回复
热议问题