windows App.config 设置,环境变量作为部分路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5303113/
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
App.config settings, environment variable as partial path
提问by Jean-Bernard Pellerin
I'm new to tinkering with app.config and xml, and am currently doing some refactoring in some code I haven't written.
Currently we have a snippet which looks like this:
我刚开始修改 app.config 和 xml,目前正在对一些我尚未编写的代码进行重构。
目前我们有一个看起来像这样的片段:
<setting name="FirstSetting" serializeAs="String">
<value>Data Source=C:\Documents and Settings\All Users\ApplicationData\Company ...;Persist Security Info=False</value>
What I'd like to do is have it instead point to something like ${PROGRAMDATA}\Company\...
我想做的是让它指向类似的东西 ${PROGRAMDATA}\Company\...
How can I achieve this, keeping in mind that PROGRAMDATA will not always point to C:\ProgramData
?
我怎样才能做到这一点,记住 PROGRAMDATA 并不总是指向C:\ProgramData
?
回答by Jean-Bernard Pellerin
I didn't really want to change it in code as per the other responses, since that removes the purpose of having it as a config setting.
我真的不想按照其他响应在代码中更改它,因为这消除了将其作为配置设置的目的。
As it turns out, %ProgramData%\Company...
is the proper way of using environment variables in this context.
事实证明,%ProgramData%\Company...
是在这种情况下使用环境变量的正确方法。
回答by troYman
use
用
Environment.ExpandEnvironmentVariables(stringFromConfig);
it replaces all existing environment variables in the string like %ProgramData% with the exact values.
它用确切的值替换字符串中的所有现有环境变量,如 %ProgramData%。
回答by Hans Passant
Yes, write it just like that in your setting. Then just substitute ${PROGRAMDATA} at runtime:
是的,在您的设置中就这样写。然后在运行时替换 ${PROGRAMDATA} :
var setting = Properties.Settings.Default.FirstSetting;
setting = setting.Replace("${PROGRAMDATA)",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
回答by Kumar
Considering the PROGRAMDATA
is an environment variable, you can access using C#
考虑到PROGRAMDATA
是一个环境变量,您可以使用 C# 访问
String EnviromentPath = System.Environment.GetEnvironmentVariable("PROGRAMDATA", EnvironmentVariableTarget.Machine);
回答by Bala R
you could use
你可以用
var programDataValue = Environment.GetEnvironmentVariable("PROGRAMDATA");
if it comes from an environment variable.
如果它来自环境变量。