Get the current path in C#


The most obvious way to retrieve the current application path is by using the following statement:


currentPath = Application.StartupPath;

That is the obvious solution but only when the project references the System.Windows.Forms library.

To avoid referencing this library (in case it is not needed), the current directory may be retrieved in many ways. See below (alternative ways are commented):

// Returns the current application path without a trailing '/'. It is the same with Application.StartupPath.
private string GetCurrentPath()
{
////returns the path with a trailing '/'
//return System.AppDomain.CurrentDomain.BaseDirectory;

////retrieve the current path (without a trailing '/')
//return Environment.CurrentDirectory;
//return System.IO.Directory.GetCurrentDirectory();

return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}

Comments

Popular posts from this blog

Write Unicode text using VBA

Calling Fortran intrinsic functions from Visual Basic

Dictionary class extensions (CopyTo, Sort) (C#)