在 .NET 中为 .config 文件使用环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/358654/
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
Using environment variables for .config file in .NET
提问by Jox
I need to specify path to dlls referenced by assembly in .config file. Problem is that path can be found in env. variable. Is it possible to use some sort of %DLLPATH% macro in .config file?
我需要在 .config 文件中指定程序集引用的 dll 的路径。问题是可以在 env 中找到路径。多变的。是否可以在 .config 文件中使用某种 %DLLPATH% 宏?
回答by Prensen
Yes, that's possible! Suppose you have something like that in your config:
是的,这是可能的!假设您的配置中有类似的内容:
<configuration>
<appSettings>
<add key="mypath" value="%DLLPATH%\foo\bar"/>
</appSettings>
</configuration>
Then you can easily get the path with:
然后你可以很容易地得到路径:
var pathFromConfig = ConfigurationManager.AppSettings["mypath"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);
ExpandEnvironmentVariables(string s)does the magic by replacing all environment variables within a string with their current values.
ExpandEnvironmentVariables(string s)通过用当前值替换字符串中的所有环境变量来实现魔术。
回答by Jon Skeet
Is this a configuration entry that you'rereading, or is .NET reading it? If you're reading it yourself, you can do the appropriate substitution yourself (using Environment.ExpandEnvironmentVariablesto do the lot or Environment.GetEnvironmentVariableif you want to be more selective).
这是您正在阅读的配置条目,还是 .NET 正在阅读它?如果你自己读它,你可以(用自己做适当的替代Environment.ExpandEnvironmentVariables做多还是Environment.GetEnvironmentVariable如果你想更选择性的)。
If it's one that .NET will be reading, I don't know of any way to make it expand environment variables. Is the config file under your control? Could you just rewrite it?
如果它是 .NET 将要阅读的,我不知道有什么方法可以让它扩展环境变量。配置文件是否在您的控制之下?你能不能重写一下?
In fact, even if you cando the substitution, is that really what you want to do? If you need to specify the full path to a DLL, I suspect you'll need to find it viathe DLLPATH (checking for its presence in each part of the path) and then subtitute %DLLPATH%\Foo.dll with the full path to Foo.dll.
事实上,即使你可以做替代,那真的是你想做的吗?如果您需要指定 DLL 的完整路径,我怀疑您需要通过DLLPATH找到它(检查它在路径的每个部分中是否存在),然后用完整路径替换 %DLLPATH%\Foo.dll到 Foo.dll。

