c# open file, path starting with %userprofile%

前端 未结 5 740
太阳男子
太阳男子 2020-12-03 06:39

I have a simple problem. I have a path to a file in user directory that looks like this:

%USERPROFILE%\\AppData\\Local\\MyProg\\settings.file
相关标签:
5条回答
  • 2020-12-03 06:58

    You can use the Environment.Username constant as well. Both of the %USERPROFILE% and this Environment variable points the same( which is the currently logged user). But if you choose this way, you have to concatenate the path by yourself.

    0 讨论(0)
  • 2020-12-03 07:04

    Try using ExpandEnvironmentVariables on the path.

    0 讨论(0)
  • 2020-12-03 07:04

    I use this in my Utilities library.

    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;
            }
        }
    }
    

    So I can simply use e.g. "string testBenchPath = MyProfile.Path("TestResults");"

    0 讨论(0)
  • 2020-12-03 07:11

    Use Environment.ExpandEnvironmentVariables on the path before using it.

    var pathWithEnv = @"%USERPROFILE%\AppData\Local\MyProg\settings.file";
    var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
    
    using(ostream = new FileStream(filePath, FileMode.Open))
    {
       //...
    }
    
    0 讨论(0)
  • 2020-12-03 07:12

    Use the Environment.ExpandEnvironmentVariables static method:

    string fileName= Environment.ExpandEnvironmentVariables(fileName);
    ostream = new FileStream(fileName, FileMode.Open);
    
    0 讨论(0)
提交回复
热议问题