views:

1094

answers:

2

Hi all

I've added a resource file to my project called CrpResource.resx . Then, after adding a text file to the resource file, I wanna to access to it and read from it by code.

any suggestion please.

+1  A: 
 _assembly = Assembly.GetExecutingAssembly();
 _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));

See following:
http://support.microsoft.com/kb/319292

Brij
What is MyNameSpace? Is it the name of the resource File?
odiseh
It is namespace of your project. In VS > Project > Properties you will get the namespace
Brij
So based on your last comment, there's no need to put the name of resource file after namespace name?
odiseh
No, You need to give in this format:<namespace name>.<file name>.<file extension>
Brij
First thanks,Second, I get this error:'Value cannot be null.Parameter name: stream'error line :_textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("Ikco.Crp.UI.CrpUser.txt"));
odiseh
You got the namespace name wrong. It is your project's namespace name, like "ClassLibrary1". Use Ildasm.exe, look at the manifest and locate the .mresource to find the full name you need to use.
Hans Passant
+2  A: 

@Brij has provided the core of the answer.

However, the difficult bit here is knowing what the resource name is - it's not always easy after embedding a file as a resource to work out its fully qualified name.

An easy way to find out is to add this line temporarily to your code:

string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();

Then run the program, and you can view the 'names' list of all available resources in the debugger.

Jason Williams
As I see in the CrpResource.Designer.cs, every thing I've added to the resource file is as a property.How can I use of this opportunity?
odiseh
You can access resources directly through their property name, but that gives you an instance of the resource rather than its raw data (e.g. an icon like 'Properties.Resources.AppIcon' would be a Bitmap object when you try to use it. You would therefore have to ask it to serialise to a MemoryStream and then read back from that MemoryStream if you wanted the raw "file" data from it)
Jason Williams