Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the C:\Users\Public directory programmatically in C#

Is it safe to programmatically reference the public folder through:

Directory = System.Environment.GetEnvironmentVariable("public")+"MyCompanyName" // etc.

or is there a better way?

Again, what if someone deletes the environment variable for public, and is this safe to use for different language OSs?

This follows: How to install to the Public directory in Windows 7 from the VS 2010 deployment Setup Project

like image 681
Jeb Avatar asked Jan 10 '11 17:01

Jeb


2 Answers

This seems a tad questionable, but it should work:

// This should give you something like C:\Users\Public\Documents
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);

var directory = new DirectoryInfo(documentsPath);

// Now this should give you something like C:\Users\Public
string commonPath = directory.Parent.FullName;
like image 145
Dan Tao Avatar answered Oct 14 '22 03:10

Dan Tao


It depends on what you want to achieve. There is a enum called SpecialFolder. You can use it to get the Path to some Directories. For Example:

System.Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)

points to "C:\Users\Public\Desktop".

IMHO, your way isn't wrong, though i would do some Exception Handling in case the EnvVar is really missing. Also you could use the ENUM with "CommonDesktopDirectory" and get rid of the "\Desktop" part.

like image 38
Stoggy Avatar answered Oct 14 '22 03:10

Stoggy