在.NET中使用.config文件的环境变量

[英]Using environment variables for .config file in .NET


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%宏?

2 个解决方案

#1


27  

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)通过将字符串中的所有环境变量替换为其当前值来实现魔力。

#2


7  

Is this a configuration entry that you're reading, or is .NET reading it? If you're reading it yourself, you can do the appropriate substitution yourself (using Environment.ExpandEnvironmentVariables to do the lot or Environment.GetEnvironmentVariable if 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 can do 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 via the 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。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2008/12/11/f2ca7a6603ca41ee169ce240e2c273.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号