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

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

问题描述

我有在我wan't在一些地方保存在%APPDATA%目录中的项目的SQL Server CE数据库。不过,我不能找到一种方法,使连接字符串中的应用程序数据路径的引用(在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>



你可以使用:

The you can use:

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天全站免登陆