How to find directory level information with C# .NET

In this post we saw how to extract system-level information using the Environment class in .NET. Another group of methods and properties of the Environment class lets you easily extract directory level information. Here come a couple of examples.

Here’s how to find the directory that the application is currently running in:

string currentDirectory = Environment.CurrentDirectory;

If you call the above method from a .NET app in Visual Studio then this will point to the deploy folder configured for the project, e.g. “C:\TestProjects\VariousCSharpLanguageConstructs\Various\Various\bin\Debug”

The GetFolderPath method accepts an Environment.SpecialFolder enumeration. Using this method will help you easily get a full file path reference to some well-known Windows folders like the MyDocuments folder:

string myDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string startMenuFolder = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
string userProfileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

It’s worth exploring the SpecialFolder enumeration and see what’s available there using IntelliSense.

Finally here’s how to find the location of the System directory:

string systemDirectory = Environment.SystemDirectory;

In my case it’s c:\Windows\system32

View all posts related to diagnostics here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to How to find directory level information with C# .NET

  1. Michael Schmid says:

    Be careful using “Environment.CurrentDirectory”, when executing application as a service. Then it results in “C:\WINDOWS\system32” (when inherited form “WindowsServiceNET”). In this case “AppDomain.CurrentDomain.BaseDirectory” is useful.
    I enjoy your articles all the time. Keep it up šŸ˜‰

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.