开发者

How to read local customconfig.xml with xElement in C#

I have added a customConfig.xml to my project.

I'm struggling to read the开发者_JAVA技巧 file into xElement because I need a file path.

Any help is greatly appreciated.

Thank you


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜