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.ArgumentNullException
with 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With