views:

24

answers:

1

Hi,

I have added a customConfig.xml to my project.

I'm struggling to read the file into xElement because I need a file path.

Any help is greatly appreciated.

Thank you

+2  A: 

If you want to compile the file to the assembly, you can do the following:

Go to the properties of the newly added file customConfig.xml and set the 'Build Action' to 'Embedded Resource'. The following piece of code allows you then to create a TextReader. The TextRead can then be used to read the file to a XDocument:

Assembly assembly = Assembly.GetExecutingAssembly();
TextReader textReader = new StreamReader(assembly.GetManifestResourceStream(String.Format("{0}.{1}", "NameSpace.Of.File", "customConfig.xml")));
XDocument doc = XDocument.Load(textReader);

foreach (XElement element in doc.Root.Nodes())
{
    // do stuff
}

If you want to have the XML file besides your assembly (not compiled into the assembly), you can set the 'Build Action' to 'None' and the 'Copy to Output Directory' to 'Copy always'. The path could be retrieved may be the following way. Did not test it.

String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

XDocument doc = XDocument.Load(strPath);

foreach (XElement element in doc.Root.Nodes())
{
    // do stuff
}

Hope this helps! Florian

Florian
@vikp: I noticed that you set the tags web-config and app-config. I am not sure what you want achieve. Maybe my proposed solutions do not fit your use case.
Florian
This makes perfect sense, thank you very much!
vikp