How to read embedded resource text file

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

    After reading all the solutions posted here. This is how I solved it:

    // How to embedded a "Text file" inside of a C# project
    //   and read it as a resource from c# code:
    //
    // (1) Add Text File to Project.  example: 'myfile.txt'
    //
    // (2) Change Text File Properties:
    //      Build-action: EmbeddedResource
    //      Logical-name: myfile.txt      
    //          (note only 1 dot permitted in filename)
    //
    // (3) from c# get the string for the entire embedded file as follows:
    //
    //     string myfile = GetEmbeddedResourceFile("myfile.txt");
    
    public static string GetEmbeddedResourceFile(string filename) {
        var a = System.Reflection.Assembly.GetExecutingAssembly();
        using (var s = a.GetManifestResourceStream(filename))
        using (var r = new System.IO.StreamReader(s))
        {
            string result = r.ReadToEnd();
            return result;
        }
        return "";      
    }
    

提交回复
热议问题