This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Getting and Setting a Program's Working Folder

When a program is executed a working folder is assigned. This may be the same folder as the program's executable or can be set to a different folder using the properties of a shortcut. The correct working folder can be found using the Environment class.

Environment Class

The Environment class is a standard class within the System namespace. It provides information relating to the current environment and operating system and, in some cases, allows the information to be modified. The Environment class contains a static property named CurrentDirectory that allows you to determine the working folder for an application.

CurrentDirectory Property

The static CurrentDirectory property returns a string containing the working folder of the executing program. If the program was started by double-clicking the executable file itself, the working folder will be the same directory as that of the program. However, if the application was launched using a Windows shortcut, the working folder returned is that defined within the shortcut's properties. Knowing the correct working folder is essential when writing information to disk to ensure that the user can predict where data files will be generated.

The following example code returns the working folder for a program.

string folder = Environment.CurrentDirectory;

The format of the folder in the returned string is different for root folders and child folders. If the working folder is the root of a drive, the returned string contains the drive name and a trailing backslash, eg. "C:\". For all other directories, the drive name and path to the working folder are provided but the trailing backslash is not present, eg. "C:\MyProgram".

Setting the Working Folder

If your program provides a setting that permits the user to override the working folder, you may want to change the environment setting from within the code. This is as simple as assigning a new folder string to the CurrentDirectory property, as in the following example:

Environment.CurrentDirectory = @"C:\";
6 January 2008