How to read embedded resource text file

前端 未结 22 2338
悲&欢浪女
悲&欢浪女 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 07:00

    This is a class which you might find very convenient for reading embedded resource files from the current Assembly:

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

提交回复
热议问题