Reading an embedded text file

后端 未结 3 2402
忘了有多久
忘了有多久 2021-02-20 13:07

I have created a full project which works perfectly. My problem concerns the setup project. When I use it on another computer, the text file cannot be found even if they are ins

3条回答
  •  深忆病人
    2021-02-20 13:45

    FIrst set the build action of the text file to "EmbeddedResource".

    Then to read the file in your code:

    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "AssemblyName.MyFile.txt";
    
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            string result = reader.ReadToEnd();
        }
    }
    

    If you can't figure out the name of the embedded resource do this to find the names and it should be obvious which your file is:

    assembly.GetManifestResourceNames();
    

    This is assuming you want the text file to be embedded in the assembly. If not, then you might just want to change your setup project to include the text file during the installation.

提交回复
热议问题