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

。_饼干妹妹 提交于 2020-01-03 13:39:08

问题


I am trying to access and read a text file, 'achInfo.txt' from my resources in Visual Studio. Some workarounds have already been listed on this site, but none of them seem to work for me. They just give me one of two errors, which I will explain later on.

Here's the entire method so far.

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;
}

My first assumption was to use Properties.Resources.achInfo, as this refers directly to the file in question. However, this throws a System.ArgumentException error, with the description 'Illegal characters in path'.

I then used the assembly solution ('Grandma_Lair' being my namespace, don't ask.') :

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

But, this throws a System.ArgumentNullExceptionwith the message 'Value cannot be null'. I have also set the access modifier on my resources to public, and I have made sure the file is set to an Embedded Resource.

Does anyone have any idea on my problem?


回答1:


Your first solution should work once you replace StreamReader with StringReader:

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

The value Properties.Resources.achInfo represents the resource that you embedded in its entirety given to you as a string, not a path to that resource (hence the "invalid characters in the path" error).

The GetManifestResourceStream approach should work too, but you need to give the method the right path, which is based, among other things, on the name of the default namespace of your project. If you add a call to assembly.GetManifestResourceNames() before trying to get your resource, and look for the exact spelling of your resource name in the debugger, you should be able to fix the null pointer exception issue as well.



来源:https://stackoverflow.com/questions/18811315/visual-studio-2012-c-reading-a-txt-file-from-resources

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