c#打开文件,以%userprofile%开头的路径

Ist*_*tel 41 c# file

我有一个简单的问题.我有一个到用户目录中的文件的路径,如下所示:

%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)

  • 因为这更通用 - 你假设传入的环境变量将始终是`%USERPROFILE%` - 如果它是其他什么呢?(这就是问题所在 - 它要求扩展环境变量 - 使用的示例是用户配置文件是偶然的). (3认同)
  • 为什么不只是`Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)`? (2认同)

Dav*_*d M 5

使用Environment.ExpandEnvironmentVariables静态方法:

string fileName= Environment.ExpandEnvironmentVariables(fileName);
ostream = new FileStream(fileName, FileMode.Open);
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记对流使用 `using` 语句。 (2认同)

And*_*tan 5

尝试在路径上使用ExpandEnvironmentVariables.


joh*_*ins 5

我在我的实用程序库中使用它。

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");”

  • 使用 [Path.Combine()](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=netframework-4.7.2) 组合路径。 (2认同)