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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With