How to read embedded resource text file

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

    Read Embedded TXT FILE on Form Load Event.

    Set the Variables Dynamically.

    string f1 = "AppName.File1.Ext";
    string f2 = "AppName.File2.Ext";
    string f3 = "AppName.File3.Ext";
    

    Call a Try Catch.

    try 
    {
         IncludeText(f1,f2,f3); 
         /// Pass the Resources Dynamically 
         /// through the call stack.
    }
    
    catch (Exception Ex)
    {
         MessageBox.Show(Ex.Message);  
         /// Error for if the Stream is Null.
    }
    

    Create Void for IncludeText(), Visual Studio Does this for you. Click the Lightbulb to AutoGenerate The CodeBlock.

    Put the following inside the Generated Code Block

    Resource 1

    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream(file1))
    using (StreamReader reader = new StreamReader(stream))
    {
    string result1 = reader.ReadToEnd();
    richTextBox1.AppendText(result1 + Environment.NewLine + Environment.NewLine );
    }
    

    Resource 2

    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream(file2))
    using (StreamReader reader = new StreamReader(stream))
    {
    string result2 = reader.ReadToEnd();
    richTextBox1.AppendText(
    result2 + Environment.NewLine + 
    Environment.NewLine );
    }
    

    Resource 3

    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream(file3))
    
    using (StreamReader reader = new StreamReader(stream))
    {
        string result3 = reader.ReadToEnd();
        richTextBox1.AppendText(result3);
    }
    

    If you wish to send the returned variable somewhere else, just call another function and...

    using (StreamReader reader = new StreamReader(stream))
    {
        string result3 = reader.ReadToEnd();
        ///richTextBox1.AppendText(result3);
        string extVar = result3;
    
        /// another try catch here.
    
       try {
    
       SendVariableToLocation(extVar)
       {
             //// Put Code Here.
       }
    
           }
    
      catch (Exception ex)
      {
        Messagebox.Show(ex.Message);
      }
    
    }
    

    What this achieved was this, a method to combine multiple txt files, and read their embedded data, inside a single rich text box. which was my desired effect with this sample of Code.

    0 讨论(0)
  • 2020-11-21 07:00

    I read an embedded resource text file use:

        /// <summary>
        /// Converts to generic list a byte array
        /// </summary>
        /// <param name="content">byte array (embedded resource)</param>
        /// <returns>generic list of strings</returns>
        private List<string> GetLines(byte[] content)
        {
            string s = Encoding.Default.GetString(content, 0, content.Length - 1);
            return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
        }
    

    Sample:

    var template = GetLines(Properties.Resources.LasTemplate /* resource name */);
    
    template.ForEach(ln =>
    {
        Debug.WriteLine(ln);
    });
    
    0 讨论(0)
  • 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());
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:02

    I know this is old, but I just wanted to point out for NETMF (.Net MicroFramework), you can easily do this:

    string response = Resources.GetString(Resources.StringResources.MyFileName);
    

    Since NETMF doesn't have GetManifestResourceStream

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