C# 如何从c中的XML文件中查找应用程序设置#
我有一个XML,如下所示:C# 如何从c中的XML文件中查找应用程序设置#,c#,xml,xml-parsing,C#,Xml,Xml Parsing,我有一个XML,如下所示: <configuration> <AppSettings> <add key="FilePath" value="c:\test" /> <add key="domain" value="google" /> </AppSettings> </configurat
<configuration>
<AppSettings>
<add key="FilePath" value="c:\test" />
<add key="domain" value="google" />
</AppSettings>
</configuration>
我想要一个快速的c:\code从.XML文件读取应用程序设置。我们不希望使用ConfigurationManager和App.config路由,因为这些密钥通过多个项目/应用程序共享,所以要求将其保留在共享位置
e、 g.静态类方法如下:
设置。GetAppKey(“文件路径”)应返回值,例如c:\test添加类进行反序列化,如下所示
[XmlRoot(ElementName = "configuration")]
public class ApplicationConfiguration
{
private Dictionary<string, string> _appSettings = new Dictionary<string, string>();
[XmlArray(ElementName = "appSettings")]
[XmlArrayItem(ElementName = "add")]
public List<AppSetting> ToolsGroups { get; set; }
public string GetAppValue(string key)
{
return ToolsGroups.Where(x => x.Key.Equals(key)).FirstOrDefault().Value;
}
}
public class AppSetting
{
[XmlAttribute(AttributeName = "key")]
public string Key { get; set; }
[XmlAttribute(AttributeName = "value")]
public string Value { get; set; }
}
@TomW OP已经声明“我们不想使用
ConfigurationManager
…”,这就是我撤回投票的原因。在任何情况下,你仍然可以使用ConfigurationManager@TomW,事实上我注意到了这条评论。它也仍然在那里:)我不确定“我们不想使用……因为这些密钥通过多个项目/应用程序共享,所以要求将其保持在共享位置”是有意义的。a) 如果您的意思是唯一性,那么为了确保您的密钥不会被其他任何东西使用,请给它一个唯一的名称。b) 如果要为现有密钥提供不同的值,也可以这样做。C)但是,如果您想将StuttSin存储在不同的文件夹中,则可能需要考虑隔离存储。使用域、程序集和计算机/用户的组合,它可以是唯一的。
bool isAppConfigFormatCorrect = false;
string appConfigFile = Path.Combine(@"..\..\..\..\Config", "app.config");
ApplicationConfiguration appConfig = new ApplicationConfiguration();
try
{
XmlDocument xmlDocumentAppConfig = new XmlDocument();
xmlDocumentAppConfig.Load(appConfigFile);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ApplicationConfiguration));
XmlReader xmlReader = XmlReader.Create(appConfigFile);
appConfig = (ApplicationConfiguration)xmlSerializer.Deserialize(xmlReader);
isAppConfigFormatCorrect = true;
}
catch (Exception ec)
{
MessageBox.Show($"Structure of the '{appConfigFile}' file is incorrect." + Environment.NewLine + $"Error Message: {ec.Message}");
}
if (isAppConfigFormatCorrect)
{
Debug.Print(appConfig.GetAppValue("FilePath"));
}