How to get application folder path in C#

By FoxLearn 12/5/2024 11:36:58 AM   147
To get the application folder path in a .NET application, you can use the Server.MapPath() method in ASP.NET or AppDomain.CurrentDomain.BaseDirectory for other types of applications.

Best way to get application folder path in C#?

The best way to get the application folder path depends on the type of application you're working with:

If you're working with legacy ASP.NET (Web Forms), you can use Server.MapPath() to get the root directory of the web application:

For example, how to get the physical path of a folder relative to your web application.

string folderPath = Server.MapPath("~/");

This will return the root directory of your web application.

For non-web applications targeting the .NET Framework, use AppDomain.CurrentDomain.BaseDirectory to get the directory of the running application:

string folderPath = AppDomain.CurrentDomain.BaseDirectory;

The AppDomain.CurrentDomain.BaseDirectory is commonly used for accessing files relative to the application's installation directory.

Use the AppContext.BaseDirectory to work with .NET Core.

string folderPath = AppContext.BaseDirectory;

This will give you the folder where the application's main executable is located, and it works across different platforms (Windows, Linux, macOS).

For ASP.NET and ASP.NET Core applications, you can use AppContext.BaseDirectory to get the root directory of the application.

string folderPath = AppContext.BaseDirectory;

For ASP.NET Core applications, this method works well when you need access to the root folder, especially when hosting in environments like IIS or Kestrel.