【发布时间】:2015-11-07 11:34:54
【问题描述】:
我有一个带有 App.config 的 WinForms .exe,其中有一堆在运行时设置并保存的用户范围设置。 我希望能够使用 WinForms 应用程序来更改和保存设置,然后单击按钮根据这些设置进行一些工作。 我还想从 sep 读取同一 .config 文件中的用户设置。控制台应用程序,以便我可以安排工作作为计划任务完成。 能够做到这一点的最佳方法是什么?
更新: 我尝试了使用 ConfigurationManager.OpenExeConfiguration 的建议,如一些答案中所述。
Configuration config = ConfigurationManager.OpenExeConfiguration("F:\\Dir\\App.exe");
但是当我尝试像这样检索用户设置时。
string result = config.AppSettings.Settings["DB"].ToString();
我得到一个空引用错误。
从 exe 中的代码但是以下正确返回数据库名称。
Properties.Settings.Default.DB
我哪里出错了?
更新 2:
因此,根据下面的一些答案,我现在可以使用以下内容从 sep 检索我感兴趣的 user.config 文件部分的原始 XML。控制台应用程序。
System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"D:\PathHere\user.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
System.Configuration.DefaultSection configSection = (System.Configuration.DefaultSection)config.GetSection("userSettings");
string result = configSection.SectionInformation.GetRawXml();
Console.WriteLine(result);
但我仍然无法仅提取我感兴趣的特定元素的值。
【问题讨论】: