Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

windows - Is There A System Defined Environment Variable For Documents Directory?

I know about the %USERPROFILE% system defined environment variable on Windows XP (and Vista and Windows 7). Is there a system defined environment variable pointing to the location of the "My Documents" directory? On XP by default it's %USERPROFILE%My Documents and on Win 7 it's %USERPROFILE%Documents. I just wanted to avoid having to test for the OS version in a Powershell script if I can avoid it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For powershell the following works:

[environment]::getfolderpath("mydocuments")

and avoiding magic strings

[Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments)

For .NET the following holds true (ie not applicable in all windows applications):

As one answer points out, there is no Environment Variable pointing to My Documents but there is Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) (C#) for .NET.

I'm adding this answer since this question comes up when googling for C#, environment variables and my documents and Justin's answer does not contain the line of code :)

Using the above mentioned line of code is the preferred way of accessing my documents in .NET :)

Copy paste this row for C# usage:

var directoryNameOfMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Note that C# needs a capital D in MyDocuments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...