How to read embedded resource text file

前端 未结 22 2382
悲&欢浪女
悲&欢浪女 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: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 FindEmbededResources(Func predicate)
        {
            if (predicate == null) throw new ArgumentNullException(nameof(predicate));
    
            return
                GetEmbededResourceNames()
                    .Where(predicate)
                    .Select(name => ReadEmbededResource(typeof(TAssembly), name))
                    .Where(x => !string.IsNullOrEmpty(x));
        }
    
        public static IEnumerable GetEmbededResourceNames()
        {
            var assembly = Assembly.GetAssembly(typeof(TAssembly));
            return assembly.GetManifestResourceNames();
        }
    
        public static string ReadEmbededResource(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();
                }
            }
        }
    }
    

提交回复
热议问题