How to read embedded resource text file

前端 未结 22 2224
悲&欢浪女
悲&欢浪女 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.

提交回复
热议问题