Expand environment variable for My Documents

wkada picture wkada · Jan 18, 2011 · Viewed 10.9k times · Source

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?

Answer

HQsnippets picture HQsnippets · Jan 18, 2011

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.