打开其他程序的配置文件配置文件、程序

2023-09-02 10:55:57 作者:记住给妳幸福的人是Me

我有一个程序的 A ,它也有,我已经添加像服务器地址,用户名和密码,某些键连接到服务器的app.config文件。这是一个控制台应用程序。现在,我想使一个UI,我做的事。在这个界面我想修改程序的 A 的的app.config的内容。我怎么做?

I have a program A, it also have an app.config file where I have added some keys like server address, username and password for connecting to a server. It is a console application. Now I want to make a UI which I have done. In that UI I want to modify the content of app.config of program A. How do I do that?

下面是我试过了,我复制的UI(基本上是一个.exe)编程的 A的目录中,其中在app.config也驻留。然后在用户界面中,我使用的 ConfigurationManager中的类的 OpenExeConfiguration 的方法,并通过该程序的 A的文件名作为参数。但它抛出和异常类型的 System.Configuration.ConfigurationErrorsException 的。

Here is what I tried, I copied the UI (basically an .exe) to program A's directory, where the app.config also resides. Then in the UI, I use the ConfigurationManager class's OpenExeConfiguration method, and passing the program A's filename as an argument. But it throws and exception of type System.Configuration.ConfigurationErrorsException.

所以,我认为我的做法是不正确。我该怎样做呢?

So I think that my approach is incorrect. How shall I do this?

编辑:哦,我忘了告诉我使用C#,.NET 3.5和VS 2008(有没有什么帮助:D)

Oh I forgot to tell I'm using C#, .NET 3.5 and VS 2008 (if that helps :D)

推荐答案

我不知道你的方法的问题(尝试添加堆栈跟踪到您的文章),但是这是我如何做到这一点:

I'm not sure about the problem with your approach (try adding the stack trace to your post) but this is how I do it:

var configMap = new ExeConfigurationFileMap {ExeConfigFilename = externalConfigurationFile};
System.Configuration.Configuration externalConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

foreach (KeyValueConfigurationElement setting in externalConfiguration.AppSettings.Settings)
{
    ...
}

currentConfiguration.Save(ConfigurationSaveMode.Full);