Reading an embedded text file

自作多情 提交于 2019-12-21 07:58:10

问题


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 inside the resource folder during the deployment!

How can I ensure that my program will find those text files after installing the software on another computer!

I have been looking for this solution but in vain. Please help me sort this out. If I can get a full code that does that i will be very happy!


回答1:


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.




回答2:


Assuming you mean that you have a file in your project that you've set as an EmbeddedResource, you want

using (var stream = Assembly.GetExecutingAssembly()
    .GetManifestResourceStream(path))
{
    ...
}

where path should be the assembly name followed by the relative path to your file in the project folder hierarchy. The separator character used is the period ..

So if you have an assembly called MyCompany.MyProject and then in that project you have a folder Test containing Image.jpg, you would use the path MyCompany.MyProject.Test.Image.jpg to get a Stream for it.




回答3:


create this function to read whatever embedded resource text file you have :

public string GetFromResources(string resourceName)
{
    Assembly assem = this.GetType().Assembly;

    using (Stream stream = assem.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }

    }
}


来源:https://stackoverflow.com/questions/18108725/reading-an-embedded-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!