Sunday, July 21, 2013

Get Path to the current directory of the executing program in C#

In C#, if you already included the System.Windows.Forms namespace, the directory from which your application is run can be obtained by

string current_dir=Application.StartupPath;

On the other hand, if you are writing a library which needs to know the directory form which the calling application is run, or you do not use the System.Windows.Forms namespace than the directory can be obtained by:

using System.IO;
using System.Diagnostics;
using System.Reflection;

string current_dir=null;
try{
   current_dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
}
catch (IOException e)
{
 throw new IOException("Can't get app root directory", e);
}

No comments:

Post a Comment