【问题标题】:C# I'm getting a FileNotFound Exception when using StreamReader to read a text file inside resourcesC# 使用 StreamReader 读取资源中的文本文件时出现 FileNotFound 异常
【发布时间】:2013-02-17 17:06:03
【问题描述】:
using (SteamReader sr = new StreamReader("text.txt"))

我还尝试不将文本文件放在.resx 文件中。

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    您使用的StreamReader 构造函数要求文件存在于磁盘上。如果文件嵌入在您的程序集中,您可以使用GetManifestResourceStream 方法。

    例如:

    // 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))
    {
        ...
    }
    

    资源嵌入到程序集中的键取决于文件在层次结构中的位置。它总是以程序集名称为前缀,然后是任何可能的子文件夹(如果有的话)。

    确保在其属性中将此文件的Build Action 设置为Embedded Resource。这里是an article,其中包含有关访问嵌入式资源的更多详细信息。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多