app.config appSettings 文件属性中的环境变量

Environment Variable in app.config appSettings file attribute

如何使用环境变量将 app.config appSettings 的外部文件指向路径?以下无法识别:

<appSettings file="%AppData%\MyApp\MySettingsFile.config" />

然而,绝对路径被识别,即使它们不在程序集输出路径的层次结构中,例如:

<appSettings file="C:\MyApp\MySettingsFile.config" />

"The path specified is relative to the main configuration file. For a Windows Forms application, this would be the binary folder (such as /bin/debug), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the web.config file is located."

https://msdn.microsoft.com/en-us/library/aa903313(v=vs.71).aspx

我猜你的场景在调用完整路径时有效,因为你的 MySettingsFile.config 仍在你的应用程序层次结构中。

您可以按照以下方式进行:

如果您在 app.config 中的更改如下:

<appSettings file="%AppData%\MyApp\MySettingsFile.config" />

然后在 .cs 文件中,使用 Environment.ExpandEnvironmentVariables 展开环境变量,如下所示:

var pathConfig = ConfigurationManager.AppSettings["file"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathConfig);

expandedPath 将具有扩展路径。