Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 457
Computoguy Avatar asked Oct 21 '22 01:10

Computoguy


1 Answers

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.

like image 73
Sergey Kalinichenko Avatar answered Oct 23 '22 19:10

Sergey Kalinichenko