[c#] How can I get the current user directory?

Using this:

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

I get this output:

"C:\\Documents and Settings\\[USER]\\Application Data"

How can I get the root directory of all users? i.e.:

"C:\\Documents and Settings\\[USER]\\"

This question is related to c# windows environment special-folders

The answer is


You can get the UserProfile path with just this:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);


$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"

Try:

System.Environment.GetEnvironmentVariable("USERPROFILE");

Edit:

If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder enumeration:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

Also very helpful, while investigating the Environment.SpecialFolder enum. Use LINQPad or create a solution and execute this code:

Enum.GetValues(typeof(Environment.SpecialFolder))
    .Cast<Environment.SpecialFolder>()
    .Select(specialFolder => new
    {
        Name = specialFolder.ToString(),
        Path = Environment.GetFolderPath(specialFolder)
    })
    .OrderBy(item => item.Path.ToLower())

Folder Paths

This is the result on my machine:

MyComputer
LocalizedResources
CommonOemLinks
ProgramFiles            C:\Program Files (x86) 
ProgramFilesX86         C:\Program Files (x86) 
CommonProgramFiles      C:\Program Files (x86)\Common Files 
CommonProgramFilesX86   C:\Program Files (x86)\Common Files 
CommonApplicationData   C:\ProgramData 
CommonStartMenu         C:\ProgramData\Microsoft\Windows\Start Menu 
CommonPrograms          C:\ProgramData\Microsoft\Windows\Start Menu\Programs 
CommonAdminTools        C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
CommonStartup           C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup 
CommonTemplates         C:\ProgramData\Microsoft\Windows\Templates 
UserProfile             C:\Users\fisch 
LocalApplicationData    C:\Users\fisch\AppData\Local 
CDBurning               C:\Users\fisch\AppData\Local\Microsoft\Windows\Burn\Burn 
History                 C:\Users\fisch\AppData\Local\Microsoft\Windows\History 
InternetCache           C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCache 
Cookies                 C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCookies 
ApplicationData         C:\Users\fisch\AppData\Roaming 
NetworkShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Network Shortcuts 
PrinterShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Printer Shortcuts 
Recent                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Recent 
SendTo                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\SendTo 
StartMenu               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu 
Programs                C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs 
AdminTools              C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
Startup                 C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 
Templates               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Templates 
Desktop                 C:\Users\fisch\Desktop 
DesktopDirectory        C:\Users\fisch\Desktop 
Favorites               C:\Users\fisch\Favorites 
MyMusic                 C:\Users\fisch\Music 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyPictures              C:\Users\fisch\OneDrive\Pictures 
MyVideos                C:\Users\fisch\Videos 
CommonDesktopDirectory  C:\Users\Public\Desktop 
CommonDocuments         C:\Users\Public\Documents 
CommonMusic             C:\Users\Public\Music 
CommonPictures          C:\Users\Public\Pictures 
CommonVideos            C:\Users\Public\Videos 
Windows                 C:\Windows 
Fonts                   C:\Windows\Fonts 
Resources               C:\Windows\resources 
System                  C:\Windows\system32 
SystemX86               C:\Windows\SysWoW64 

("fisch" is the first 5 letters of my last name. This is the user name assigned when signing in with a Microsoft Account.)


Try:

System.IO.Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName/

Messing around with environment variables or hard-coded parent folder offsets is never a good idea when there is a API to get the info you want, call SHGetSpecialFolderPath(...,CSIDL_PROFILE,...)


Environment.GetEnvironmentVariable("userprofile")

Trying to navigate up from a named SpecialFolder is prone for problems. There are plenty of reasons that the folders won't be where you expect them - users can move them on their own, GPO can move them, folder redirection to UNC paths, etc.

Using the environment variable for the userprofile should reflect any of those possible issues.


you can use the following code:

if(Platform.Equals("WinCE"))
{
    m_CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
}
else if(Platform.Equals("Win32NT"))
{
    m_CurrentPath = Directory.GetCurrentDirectory();
}

more information see: Get Current Directory Path in both WinXP and WinCE with C#


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to environment

Using Pip to install packages to Anaconda Environment How to generate .env file for laravel? Set windows environment variables with a batch file Setting up Eclipse with JRE Path Changing default shell in Linux How to find the path of the local git repository when I am possibly in a subdirectory Windows 7 environment variable not working in path Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'? Java system properties and environment variables Environment variables in Eclipse

Examples related to special-folders

How can I get the current user directory?