How to read embedded resource text file

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

    public class AssemblyTextFileReader
    {
        private readonly Assembly _assembly;
    
        public AssemblyTextFileReader(Assembly assembly)
        {
            _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
        }
    
        public async Task 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;
        }
    }
    

提交回复
热议问题