如何从diff应用程序中读取app.config中的用户设置?

时间:2009-12-03 16:17:48

标签: c# winforms

我有一个带有App.config的WinForms .exe,它有一堆在运行时设置并保存的用户范围设置。 我希望能够使用WinForms应用程序更改和保存设置,然后单击按钮根据这些设置执行一些工作。 我还想从sep中读取同一.config文件中的用户设置。控制台应用程序,所以我可以安排工作作为计划任务完成。 能够做到这一点的最佳方法是什么?

更新: 我尝试了使用ConfigurationManager.OpenExeConfiguration的建议,如某些答案所述。

Configuration config = ConfigurationManager.OpenExeConfiguration("F:\\Dir\\App.exe");

但是当我尝试检索这样的用户设置时。

string result = config.AppSettings.Settings["DB"].ToString();

我收到Null参考错误。

从exe中的代码中,以下正确返回数据库名称。

Properties.Settings.Default.DB

我哪里错了?

更新2:

基于下面的一些答案,我现在可以使用以下内容从sep中检索我感兴趣的user.config文件部分的原始XML。 ConsoleApp。

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);

但我仍然无法为我感兴趣的特定元素提取值。

6 个答案:

答案 0 :(得分:6)

这应该这样做:

var clientSettingsSection = (System.Configuration.ClientSettingsSection)(ConfigurationManager.GetSection("userSettings/YourApplicationName.Properties.Settings"));
var setting = clientSettingsSection.Settings.Get("yourParamName_DB_");
string yourParamName_DB = ((setting.Value.ValueXml).LastChild).InnerText.ToString();

答案 1 :(得分:2)

您可以使用ConfigurationManager类打开另一个可执行文件的配置文件。

Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();

答案 2 :(得分:0)

请参阅ConfigurationManager.OpenExeConfiguration

答案 3 :(得分:0)

如果您是按用户设置这些值,则可能需要使用ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel)方法,而不是现在使用的当前方法。

答案 4 :(得分:0)

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Environment.CurrentDirectory + "\\MyApp.exe.config";
//i have config in the same directory as my another app         
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var settingsSection = (System.Configuration.ClientSettingsSection)config.GetSection("userSettings/MyApp.Properties.Settings");
var setting = settingsSection.Settings.Get("MySetting");
var param = ((setting.Value.ValueXml).LastChild).InnerText.ToString();

答案 5 :(得分:-1)

如果您知道配置文件的路径,请尝试:

System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(“configPath”);

string myValue = config.AppSettings.Settings [“myValue”] .Value;