C# I'm getting a FileNotFound Exception when using StreamReader to read a text file inside resources

前端 未结 1 679
小鲜肉
小鲜肉 2021-01-29 11:18
using (SteamReader sr = new StreamReader(\"text.txt\"))

I also tried to don\'t put the text file on the .resx file.

相关标签:
1条回答
  • 2021-01-29 11:56

    The StreamReader constructor that you are using expects the file to exist on the disk. If the file is embedded inside your assembly you could use the GetManifestResourceStream method.

    For example:

    // Get the current assembly. If the file is embedded inside a different
    // assembly you will need to get that assembly
    var assembly = Assembly.GetExecutingAssembly();
    using (var stream = assembly.GetManifestResourceStream("AssemblyName.test.txt"))
    using (var sr = new StreamReader(stream))
    {
        ...
    }
    

    The key under which the resource is embedded into your assembly will depend on where is the file situated in the hierarchy. It is always prefixed with the assembly name and then any possible subfolders if you have some.

    Make sure that the Build Action is set to Embedded Resource for this file in its properties. And here's an article with more details about accessing embedded resources.

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