繁体   English   中英

Visual Studio 2012 - C#:从资源中读取“.txt”文件

[英]Visual Studio 2012 - C#: Reading a '.txt' File From Resources

我试图从Visual Studio中的资源访问和读取文本文件'achInfo.txt'。 这个网站上已经列出了一些解决方法,但它们似乎都不适用于我。 他们只给我两个错误中的一个,我将在后面解释。

到目前为止,这是整个方法。

private string[] GetAchMetadata(short element)
{
    string[] temp = { "", "" };
    string cLine;
    try
    {
        StreamReader sr = new StreamReader(Properties.Resources.achInfo);
        while (!sr.EndOfStream)
        {
            cLine = sr.ReadLine();
            if (Microsoft.VisualBasic.Information.IsNumeric(cLine))
            {
                if (int.Parse(cLine) == element)
                {
                    temp[0] = cLine;
                    temp[1] = sr.ReadLine();
                    return temp;
                }
            }
        }

    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine("There was a problem in collecting data.");
        System.Diagnostics.Debug.Write(e);
    }

    return temp;
}

我的第一个假设是使用Properties.Resources.achInfo ,因为它直接引用了相关文件。 但是,这会引发System.ArgumentException错误,其描述为“路径中的非法字符”。

然后我使用了汇编解决方案('Grandma_Lair'是我的命名空间,不要问。'):

Assembly asm;
asm = Assembly.GetExecutingAssembly();
StreamReader sr = new StreamReader(asm.GetManifestResourceStream("Grandma_Lair.achInfo.txt"));

但是,这会抛出一个System.ArgumentNullException ,并显示消息“Value not not null”。 我还将我的资源上的访问修饰符设置为public,并确保将该文件设置为Embedded Resource。

有没有人对我的问题有任何想法?

使用StringReader替换StreamReader ,您的第一个解决方案应该可以正常工作:

StringReader sr = new StringReader(Properties.Resources.achInfo);

Properties.Resources.achInfo表示您作为字符串给予的整体嵌入的资源,而不是该资源的路径(因此“路径中的无效字符”错误)。

GetManifestResourceStream方法也应该工作,但是您需要为方法提供正确的路径,该路径除了其他之外,还基于项目的默认命名空间的名称。 如果在尝试获取资源之前添加对assembly.GetManifestResourceNames()的调用,并在调试器中查找资源名称的确切拼写,则应该能够修复空指针异常问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM