C# app.config/web.config 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/603009/
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
Variables within app.config/web.config
提问by DeeStackOverflow
Is it is possible to do something like the following in the app.config
or web.config
files?
是否可以在app.config
或web.config
文件中执行以下操作?
<appSettings>
<add key="MyBaseDir" value="C:\MyBase" />
<add key="Dir1" value="[MyBaseDir]\Dir1"/>
<add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
I then want to access Dir2 in my code by simply saying:
然后我想通过简单地说来访问我的代码中的 Dir2:
ConfigurationManager.AppSettings["Dir2"]
This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config
.
(I know I can manage all the concatenation in code, but I prefer it this way).
当我将应用程序安装在不同的服务器和位置时,这将对我有所帮助,其中我只需要更改整个app.config
. (我知道我可以在代码中管理所有连接,但我更喜欢这种方式)。
采纳答案by Arjan Einbu
Good question.
好问题。
I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.
我不认为有。我相信,如果有一种简单的方法,那将会是众所周知的,而且我看到 Microsoft 在 Visual Studio 2010 中创建了一种机制,用于部署不同的配置文件以进行部署和测试。
With that said, however; I have found that you in the ConnectionStrings
section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...
然而,话虽如此;我发现您在该ConnectionStrings
部分中有一种名为“|DataDirectory|”的占位符。也许你可以看看那里有什么工作......
Here's a piece from machine.config
showing it:
这是machine.config
展示它的一段:
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
回答by Sergio
Inside <appSettings>
you can create application keys,
在里面<appSettings>
你可以创建应用程序密钥,
<add key="KeyName" value="Keyvalue"/>
Later on you can access these values using:
稍后您可以使用以下方法访问这些值:
ConfigurationManager.AppSettings["Keyname"]
回答by Micha?l Carpentier
I don't think you can declare and use variables to define appSettings keys within a configuration file. I've always managed concatenations in code like you.
我认为您不能在配置文件中声明和使用变量来定义 appSettings 键。我一直像你一样管理代码中的串联。
回答by Andrew Barrett
I'm struggling a bit with what you want, but you can add an override file to the app settings then have that override file set on a per environment basis.
我对你想要的东西有点挣扎,但你可以在应用程序设置中添加一个覆盖文件,然后在每个环境的基础上设置该覆盖文件。
<appSettings file="..\OverrideSettings.config">
回答by JoshBerke
You have a couple of options. You could do this with a build / deploy step which would process your configuration file replacing your variables with the correct value.
你有几个选择。您可以使用构建/部署步骤来执行此操作,该步骤将处理您的配置文件,用正确的值替换您的变量。
Another option would be to define your own Configuration section which supported this. For example imagine this xml:
另一种选择是定义您自己的支持这一点的配置部分。例如想象这个xml:
<variableAppSettings>
<variables>
<add key="@BaseDir" value="c:\Programs\Widget"/>
</variables>
<appSettings>
<add key="PathToDir" value="@BaseDir\Dir1"/>
</appSettings>
</variableAppSettings>
Now you would implement this using custom configuration objects which would handle replacing the variables for you at runtime.
现在,您将使用自定义配置对象来实现这一点,这些对象将在运行时为您处理替换变量。
回答by Scott Weinstein
I thought I just saw this question.
我以为我刚看到这个问题。
In short, no, there's no variable interpolation within an application configuration.
简而言之,不,应用程序配置中没有变量插值。
You have two options
你有两个选择
- You could roll your own to substitute variables at runtime
- At build time, massage the application configuration to the particular specifics of the target deployment environment. Some details on this at dealing with the configuration-nightmare
- 您可以自己滚动以在运行时替换变量
- 在构建时,根据目标部署环境的特定细节调整应用程序配置。处理配置噩梦时的一些细节
回答by cjk
For rolling out products where we need to configure a lot of items with similar values, we use small console apps that read the XML and update based on the parameters passed in. These are then called by the installer after it has asked the user for the required information.
为了推出我们需要配置许多具有相似值的项目的产品,我们使用小型控制台应用程序读取 XML 并根据传入的参数进行更新。然后安装程序在向用户询问需要的信息。
回答by Matt Hamsmith
A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your app.config
/ web.config
file, you can have this:
一个稍微复杂但更灵活的替代方法是创建一个表示配置部分的类。在您的app.config
/web.config
文件中,您可以拥有以下内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section must be the first section within the <configuration> node -->
<configSections>
<section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
</configSections>
<DirectoryInfo>
<Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
</DirectoryInfo>
</configuration>
Then, in your .NET code (I'll use C# in my example), you can create two classes like this:
然后,在您的 .NET 代码中(我将在我的示例中使用 C#),您可以创建两个这样的类:
using System;
using System.Configuration;
namespace MyProjectNamespace {
public class DirectoryInfoConfigSection : ConfigurationSection {
[ConfigurationProperty("Directory")]
public DirectoryConfigElement Directory {
get {
return (DirectoryConfigElement)base["Directory"];
}
}
public class DirectoryConfigElement : ConfigurationElement {
[ConfigurationProperty("MyBaseDir")]
public String BaseDirectory {
get {
return (String)base["MyBaseDir"];
}
}
[ConfigurationProperty("Dir1")]
public String Directory1 {
get {
return (String)base["Dir1"];
}
}
[ConfigurationProperty("Dir2")]
public String Directory2 {
get {
return (String)base["Dir2"];
}
}
// You can make custom properties to combine your directory names.
public String Directory1Resolved {
get {
return System.IO.Path.Combine(BaseDirectory, Directory1);
}
}
}
}
Finally, in your program code, you can access your app.config
variables, using your new classes, in this manner:
最后,在您的程序代码中,您可以app.config
使用您的新类以这种方式访问您的变量:
DirectoryInfoConfigSection config =
(DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved; // This value will equal "C:\MyBase\Dir1"
回答by Martin
Usally, I end up writing a static class with properties to access each of the settings of my web.config.
通常,我最终会编写一个带有属性的静态类来访问我的 web.config 的每个设置。
public static class ConfigManager
{
public static string MyBaseDir
{
return ConfigurationManager.AppSettings["MyBaseDir"].toString();
}
public static string Dir1
{
return MyBaseDir + ConfigurationManager.AppSettings["Dir1"].toString();
}
}
Usually, I also do type conversions when required in this class. It allows to have a typed access to your config, and if settings change, you can edit them in only one place.
通常,我也会在本课程中需要时进行类型转换。它允许对您的配置进行键入访问,如果设置发生更改,您只能在一个地方编辑它们。
Usually, replacing settings with this class is relatively easy and provides a much greater maintainability.
通常,用这个类替换设置相对容易,并且提供了更好的可维护性。
回答by Rich
I would recommend following Matt Hamsmith's solution. If it's an issue to implement, then why not create an extension method that implements this in the background on the AppSettings class?
我建议遵循 Matt Hamsmith 的解决方案。如果这是一个需要实现的问题,那么为什么不在 AppSettings 类的后台创建一个扩展方法来实现它呢?
Something like:
就像是:
public static string GetValue(this NameValueCollection settings, string key)
{
}
Inside the method you search through the DictionaryInfoConfigSection using Linq and return the value with the matching key. You'll need to update the config file though, to something along these lines:
在该方法中,您使用 Linq 搜索 DictionaryInfoConfigSection 并返回具有匹配键的值。不过,您需要将配置文件更新为以下内容:
<appSettings>
<DirectoryMappings>
<DirectoryMap key="MyBaseDir" value="C:\MyBase" />
<DirectoryMap key="Dir1" value="[MyBaseDir]\Dir1"/>
<DirectoryMap key="Dir2" value="[MyBaseDir]\Dir2"/>
</DirectoryMappings>
</appSettings>