【发布时间】:2012-10-26 09:48:21
【问题描述】:
我有一个桌面 WPF 应用程序,它使用 Entity Framework 4.1 Code First 方法来管理数据。
EF 将连接字符串添加到 App.config 文件中,我希望无法在运行时更改此连接字符串。
场景是这样的:
当我部署应用程序时,它在 App.config 文件中有一个默认连接字符串。用户运行应用程序,由于连接字符串可能对用户无效(因为服务器名称、用户 ID 和密码),我将显示一个服务器配置窗口。
用户将在此处输入有关其连接的有效信息,然后按确定。然后我将能够更改 App.config 文件并将用户的新有效信息保存到该文件中。
问题:
如果我使用 ConfigurationManager 更改它,更改将是临时的,这意味着文件没有保存,更改是在内存中进行的。
如果我将 App.config 文件读入流中,在内存中进行必要的更改,删除物理文件并再次将内存中的流另存为 App.config,Windows 将不允许我对 ProgramFiles 文件夹下的文件进行更改。
这里最好的方法是什么?
编辑:问题又来了!
我用这种方法修改了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(); 方法调用抛出错误提示
“访问“C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config” 被拒绝。”
我知道“程序文件”下的文件是不可变的,那么我该如何处理呢?
【问题讨论】:
-
@Sandeep,谢谢。 Kevin Aenmey 在您的链接上的第二个答案似乎是正确的方法。
标签: c# wpf deployment runtime app-config