Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand environment variable for My Documents

I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

like image 722
wkada Avatar asked Jan 18 '11 17:01

wkada


2 Answers

No there is no environment variable for the MyDocuments special folder (the same is true for most members of the SpecialFolder enumeration).

Check out this snippet, it might be exactly what you are searching for.

It allows you to do something like that:

string fullPath = SpecialFolder.ExpandVariables(@"%MyDocuments%\Foo");

Note: SpecialFolder.ExpandVariables is a static method of a helper class introduced in the above snippet.

like image 74
HQsnippets Avatar answered Sep 21 '22 13:09

HQsnippets


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);
like image 40
Lucas Avatar answered Sep 24 '22 13:09

Lucas