Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the path of the home directory in C#?

Tags:

c#

.net

People also ask

What is the path to home directory?

By default, all non-root user home directories are located in a directory named "home", below the / (root) directory - in the path of /home. For example, for a Linux user named cwest, the home directory is in the path of /home/cwest. The home directory for the bbest user is in the path of /home/bbest.

How do I access my home directory?

Try cd /root . ~ is normally just a shorthand for the home directory, so if you are the regular user person then cd ~ is the same as cd /home/person .

How do I find the home directory of a user?

Find User's Home Directory Using Cd Command You can also use $HOME command, which takes you to the Home directory as a variable. Not only do we understand the concept of the Linux user's home directory, but we can navigate to it from any directory path.


You are looking for Environment.SpecialFolder.UserProfile which refers to C:\Users\myname on Windows and /home/myname on Unix/Linux:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

Note that Environment.SpecialFolder.Personal is My Documents (or Documents in win7 and above), but same as home directory on Unix/Linux.


Environment.SpecialFolder.Personal doesn't actually return the home folder, it returns the My Documents folder. The safest way to get the home folder on Win32 is to read %HOMEDRIVE%%HOMEPATH%. Reading environment variables is actually very portable to do (across Unix and Windows), so I'm not sure why the poster wanted to not do it.

Edited to add: For crossplatform (Windows/Unix) C#, I'd read $HOME on Unix and OSX and %HOMEDRIVE%%HOMEPATH% on Windows.


I believe what you are looking for is:

System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

For reference, it is infact contained in mscorlib.


In DotNetCore 1.1 System.Environment.SpecialFolder does not exist. It might exist in 2.0-beta. Until then, to do this you can use the following:

var envHome = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "HOMEPATH" : "HOME";
var home = Environment.GetEnvironmentVariable(envHome);`