Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading embedded XML file c#

Tags:

c#

xml

How can I read from an embedded XML file - an XML file that is part of a c# project? I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.

Any idea?

like image 796
Pila Avatar asked May 12 '10 15:05

Pila


People also ask

How do you read embedded files?

Method 1: Add existing file, set property to Embedded Resource. Add the file to your project, then set the type to Embedded Resource . NOTE: If you add the file using this method, you can use GetManifestResourceStream to access it (see answer from @dtb).

What is embedded resource in C#?

Embedded files are called as Embedded Resources and these files can be accessed at runtime using the Assembly class of the System. Reflection namespace. Any file within the project can be made into an embedded file.


1 Answers

  1. Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)

  2. Set the "Build Action" property for the XML file to "Embedded Resource".

  3. Use the following code to retrieve the file contents at runtime:

    public string GetResourceTextFile(string filename) {     string result = string.Empty;      using (Stream stream = this.GetType().Assembly.                GetManifestResourceStream("assembly.folder."+filename))     {         using (StreamReader sr = new StreamReader(stream))         {             result = sr.ReadToEnd();         }     }     return result; } 

Whenever you want to read the file contents, just use

string fileContents = GetResourceTextFile("myXmlDoc.xml"); 

Note that "assembly.folder" should be replaced with the project name and folder containing the resource file.

Update

Actually, assembly.folder should be replaced by the namespace in which a class created in the same folder as the XML file would have by default. This is typically defaultNamespace.folder0.folder1.folder2......

like image 120
3Dave Avatar answered Oct 02 '22 14:10

3Dave