C# 获取 %AppData% 的路径 [英] C# getting the path of %AppData%
问题描述
C# 2008 SP1
C# 2008 SP1
我正在使用以下代码:
dt.ReadXml("%AppData%\DateLinks.xml");
但是,我收到一个异常,指向我的应用程序运行的位置:
However, I am getting an exception that points to the location of where my application is running from:
找不到路径的一部分'D:ProjectsSubVersionProjectsCatDialerinDebug\%AppData%DateLinks.xml'.
Could not find a part of the path 'D:ProjectsSubVersionProjectsCatDialerinDebug\%AppData%DateLinks.xml'.
我认为 %AppData%
应该找到相对路径.当我去 Start|Run|%AppData%
时,windows 资源管理器会将我带到该目录.
I thought the %AppData%
should find the relative path. When I go Start|Run|%AppData%
windows explorer takes me to that directory.
我无法输入完整路径,因为每个客户端计算机上的用户都不同.
I can not put the full path in, as the user is different on each client machine.
推荐答案
要获取AppData目录,最好使用GetFolderPath
方法:
To get the AppData directory, it's best to use the GetFolderPath
method:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
(如果不存在,必须添加using System
).
(must add using System
if not present).
%AppData%
是一个环境变量,它们不会在 .NET 中的任何地方自动扩展,尽管您可以明确使用 Environment.ExpandEnvironmentVariable
方法来做到这一点.但是,我仍然强烈建议您使用 GetFolderPath
,因为正如 Johannes Rössel 在评论中指出的那样,在某些情况下可能不会设置 %AppData%
.
%AppData%
is an environment variable, and they are not automatically expanded anywhere in .NET, although you can explicitly use the Environment.ExpandEnvironmentVariable
method to do so. I would still strongly suggest that you use GetFolderPath
however, because as Johannes Rössel points out in the comment, %AppData%
may not be set in certain circumstances.
最后,创建示例中所示的路径:
Finally, to create the path as shown in your example:
var fileName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "DateLinks.xml");
这篇关于C# 获取 %AppData% 的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!