Expand environment variable for My Documents

后端 未结 6 2139
星月不相逢
星月不相逢 2021-01-04 06:19

I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be r

6条回答
  •  既然无缘
    2021-01-04 07:17

    Is there an environment variable that equals SpecialFolder.MyDocuments?

    Short answer: No.

    Long answer:
    Still no. You can type "set" into a Command Prompt to see all you current environment variables. I couldn't find any for my documents folder on my profile (tried on WinXP and Win7).

    Also, expanding "%USERPROFILE%\My Documents" would be incorrect since the user's documents folder could be anywhere else (e.g., on my home PC I always change mine to D:\Documents).

    If you really need to use environment variables, one solution might be to set the variable yourself:

    // this environment variable is created for the current process only
    string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    Environment.SetEnvironmentVariable("MYDOCUMENTS", documents);
    

    Another solution might be to use a "fake" environment variable in the path and expand it yourself, something like:

    string path = "%MYDOCUMENTS%\\Foo"; // read from config
    
    // expand real env. vars
    string expandedPath1 = Environment.ExpandEnvironmentVariables(path);
    
    // expand our "fake" env. var
    string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string expandedPath2 = path.Replace("%MYDOCUMENTS%", documents);
    

提交回复
热议问题