如何在 C# 中使用 xElement 读取本地 customconfig.xml

发布于 2024-09-04 15:32:29 字数 107 浏览 2 评论 0原文

我已将 customConfig.xml 添加到我的项目中。

我正在努力将文件读入 xElement,因为我需要一个文件路径。

非常感谢任何帮助。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆° 2024-09-11 15:32:29

如果要将文件编译为程序集,可以执行以下操作:

转到新添加的文件 customConfig.xml 的属性,并将“构建操作”设置为“嵌入资源”。下面的代码允许您创建一个 TextReader。
然后,可以使用 TextRead 将文件读取到 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
}

如果您希望在程序集之外拥有 XML 文件(未编译到程序集中),则可以将“构建操作”设置为“无”,将“复制到”设置为输出目录”更改为“始终复制”。可以通过以下方式检索路径。没有测试过。

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
}

希望这有帮助!
弗洛里安

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文