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

C# 如何在C中使用xElement读取本地customconfig.xml#,c#,xml,web-config,app-config,config,C#,Xml,Web Config,App Config,Config,我已将customConfig.xml添加到我的项目中 我正在努力将文件读入xElement,因为我需要一个文件路径 非常感谢您的帮助 谢谢如果要将文件编译到程序集,可以执行以下操作: 转到新添加的文件customConfig.xml的属性,并将“构建操作”设置为“嵌入式资源”。下面的代码允许您创建一个文本阅读器。 然后可以使用TextRead将文件读取到XDocument: Assembly assembly = Assembly.GetExecutingAssembly(); TextRea

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

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

非常感谢您的帮助


谢谢

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

转到新添加的文件customConfig.xml的属性,并将“构建操作”设置为“嵌入式资源”。下面的代码允许您创建一个文本阅读器。 然后可以使用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
}
希望这有帮助!
Florian

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

转到新添加的文件customConfig.xml的属性,并将“构建操作”设置为“嵌入式资源”。下面的代码允许您创建一个文本阅读器。 然后可以使用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
}
希望这有帮助!
Florian

@vikp:我注意到你设置了标签WebConfig和AppConfig。我不确定你想要实现什么。也许我建议的解决方案不适合您的用例。@vikp:我注意到您设置了标记“web配置”和“应用配置”。我不确定你想要实现什么。也许我提出的解决方案不适合您的用例。