如何在 (App.config) connectionString 中使用应用程序数据 [英] How to use Application Data in an (App.config) connectionString

查看:27
本文介绍了如何在 (App.config) connectionString 中使用应用程序数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中有一个 SQL Server CE 数据库,我不想将它存储在 %AppData% 目录中的某处.但是我找不到在连接字符串中引用应用程序数据路径的方法(在 App.Config 中)

I've got an SQL Server CE database in a project that I wan't to store somewhere in the %AppData% directory. However I can't find a way to make a reference to the Application Data path in the connection string (in the App.Config)

<?xml version="1.0"?>
<configuration>
  <configSections>
  </configSections>
  <connectionStrings>
    <add name="EntityConnectionString" connectionString="metadata=res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl;provider=System.Data.SqlServerCe.3.5;provider connection string=&quot;Data Source=|ApplicationData|\Entities.sdf&quot;" providerName="System.Data.EntityClient"/>
  </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
</configuration>

到目前为止,我了解到:不支持 %APPDATA% 并且使用设置类(如建议的那样)也不起作用(设置类在已经抛出异常时未构造).

So far I learned that: %APPDATA% is not supported and using the settings class (like suggested) won't work either (the settings class isn't constructed at the time the exception is already thrown).

是否可以在 connectionString 属性(在 App.Config 中)中使用应用程序数据文件夹(或其他特殊文件夹)?

Is it possible to use the application data folder (or another special folder) in the connectionString property (in the App.Config)?

注意:似乎我正在寻找一种解决方案来尽早修改连接字符串(在代码中),而不是本机 App.Config 解决方案.

Note: it seems like I'm searching for an solution to modify the connection string (in code) as early as possible rather than an native App.Config solution.

推荐答案

使用您的自定义构建环境变量支持:

Use your custom build environment variable support:

让你拥有:

<connectionStrings>
    <add name="My" connectionString="..;Data Source=|%AppData%|\Entities.sdf;.." />
</connectionStrings>

您可以使用的:

using System.Configuration; // requires reference to System.Configuration.dll

ConfigurationManager.ConnectionStrings["EntityConnectionString"].ConnectionString.Replace("%AppData%", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

接下来你可以支持多个环境变量:

Next way you can support several environment variables:

var vars = new Dictionary<string, string>
{
    { "%AppData%", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    { "%Temp%", Environment.GetFolderPath(SpecialFolder.Temp) },
    // etc..
    { "%YourNonStandardVar", "YourNonStandartPath" }
};

var result = ConfigurationManager.ConnectionStrings["YourString"].ConnectionString
foreach (var v in vars)
    result = result.Replace(v.Key, v.Value);

这篇关于如何在 (App.config) connectionString 中使用应用程序数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆