我有一个简单的问题.我有一个到用户目录中的文件的路径,如下所示:
%USERPROFILE%\AppData\Local\MyProg\settings.file
Run Code Online (Sandbox Code Playgroud)
当我尝试将其作为文件打开时
ostream = new FileStream(fileName, FileMode.Open);
Run Code Online (Sandbox Code Playgroud)
它吐出错误,因为它尝试添加%userprofile%
到当前目录,因此它变为:
C:\Program Files\MyProg\%USERPROFILE%\AppData\Local\MyProg\settings.file
Run Code Online (Sandbox Code Playgroud)
如何让它识别以路径开头的路径%USERPROFILE%
是绝对路径而不是相对路径?
PS:我不能用
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Run Code Online (Sandbox Code Playgroud)
因为我只需要按名称打开文件.用户指定名称.如果用户指定"settings.file",我需要打开一个相对于程序目录的文件,如果用户指定一个开头的路径%USERPROFILE%
或其他一些转换为C:\的东西,我也需要打开它!
Ode*_*ded 79
使用Environment.ExpandEnvironmentVariables
使用前的道路上.
var pathWithEnv = @"%USERPROFILE%\AppData\Local\MyProg\settings.file";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using(ostream = new FileStream(filePath, FileMode.Open))
{
//...
}
Run Code Online (Sandbox Code Playgroud)
使用Environment.ExpandEnvironmentVariables
静态方法:
string fileName= Environment.ExpandEnvironmentVariables(fileName);
ostream = new FileStream(fileName, FileMode.Open);
Run Code Online (Sandbox Code Playgroud)
我在我的实用程序库中使用它。
using System;
namespace Utilities
{
public static class MyProfile
{
public static string Path(string target)
{
string basePath =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
@"\Automation\";
return basePath + target;
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以简单地使用例如“string testBenchPath = MyProfile.Path("TestResults");”