在 WPF 中需要可更改的 App.config 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13251077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:05:50  来源:igfitidea点击:

Need changable App.config file in WPF

c#wpfdeploymentruntimeapp-config

提问by Mert Akcakaya

I have a desktop WPF application which uses Entity Framework 4.1 Code First approach to manage data.

我有一个桌面 WPF 应用程序,它使用 Entity Framework 4.1 Code First 方法来管理数据。

EF adds a connection string to the App.config file and I wan't to be able to change this connection string at runtime.

EF 向 App.config 文件添加了一个连接字符串,但我无法在运行时更改此连接字符串。

Scenario is like this:

场景是这样的:

When I deploy the application it has a default connection string in the App.config file. The user runs the application and since the connection string will probably be invalid for the user (because of server name, user id and password) I will display a server configuration window.

当我部署应用程序时,它在 App.config 文件中有一个默认的连接字符串。用户运行应用程序,由于连接字符串可能对用户无效(因为服务器名称、用户 ID 和密码),我将显示服务器配置窗口。

Here user will enter the valid information about his connection and press OK. I will then be able to change the App.config file and save the user's new valid information to the file.

用户将在此处输入有关其连接的有效信息,然后按 OK。然后,我将能够更改 App.config 文件并将用户的新有效信息保存到该文件中。

Problems:

问题:

If I change it using ConfigurationManager, the changes will be temporary meaning that the file is not saved, changes are made in memory.

如果我使用 ConfigurationManager 更改它,更改将是临时的,这意味着文件不会保存,更改是在内存中进行的。

If I read the App.config file into a stream, make required changes in the memory, delete physical file and save the in memory stream as App.config again, Windows will not let me make changes to files under ProgramFiles folder.

如果我将 App.config 文件读入流中,在内存中进行所需的更改,删除物理文件并将内存中的流再次保存为 App.config,Windows 将不允许我对 ProgramFiles 文件夹下的文件进行更改。

What is would be the best approach here?

这里最好的方法是什么?

EDIT: Problem Again!

编辑:问题又来了!

After I modify the App.config file with this method:

在我用这种方法修改 App.config 文件后:

private void ApplyChangesToConnectionString()
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
    config.Save(); // This line throws an exception
    ConfigurationManager.RefreshSection("connectionStrings");   
}

config.Save();method call throws an error saying

config.Save();方法调用抛出一个错误说

"Access to "C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config" is denied."

“对“C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config”的访问被拒绝。”

I know that files under "Program files" are immutable, so how can I handle this?

我知道“程序文件”下的文件是不可变的,那么我该如何处理呢?

回答by Mert Akcakaya

I couldn't modify ConfigurationManager.ConnectionStrings["key"]object, because it is readonly.

我无法修改ConfigurationManager.ConnectionStrings["key"]对象,因为它是只读的。

So I decided to add a new connection string to my App.config file so it looks like this:

所以我决定在我的 App.config 文件中添加一个新的连接字符串,看起来像这样:

<connectionStrings>
<add name="SomeUniqueName" connectionString="Data Source=(local)\SQLExpress;Initial Catalog=MyDb;User Id=sa;Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

and then changed my DbContext constructor to take newly added connection string like this:

然后将我的 DbContext 构造函数更改为采用新添加的连接字符串,如下所示:

public MyContext()
        : base("name=SomeUniqueName")
    {

    }

Here, the value of name attribute at connection string and constructor must match.

此处,连接字符串和构造函数中的 name 属性值必须匹配。

Then to change this newly added connection string at runtime I used a method like this:

然后在运行时更改这个新添加的连接字符串,我使用了这样的方法:

private void ApplyChangesToConnectionString()
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
        connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
        config.Save();
        ConfigurationManager.RefreshSection("connectionStrings");   
    }

回答by lstern

App.config is not the proper place to do this since it's a global configuration used by the application.

App.config 不是执行此操作的正确位置,因为它是应用程序使用的全局配置。

I recommend you to save the settings per user. See this related question : c# - approach for saving user settings in a WPF application?

我建议您保存每个用户的设置。请参阅此相关问题:c# - 在 WPF 应用程序中保存用户设置的方法?

回答by Nick

App.config isthe correct approach in my opinion, however I wouldn't rely on writing the file physically yourself. Instead, allow the framework to do the heavy lifting for you.

App.config在我看来正确的方法,但是我不会依赖于自己亲自编写文件。相反,让框架为您完成繁重的工作。

Check out the sample here.

此处查看示例。

EDIT: Glad Sandeep's comment above has helped you. Feel free to check out that link too if you want a bit more information!

编辑:很高兴 Sandeep 上面的评论对您有所帮助。如果您想了解更多信息,请随时查看该链接!