Friday, May 15, 2009

C# - Application.StartupPath - How to get the path for the executable file that started the application?

If you want to have access to the path of running application, there is a property that can give you the path. As an example this path can contain other files or folders to keep related data files to youe application and in this way you can work with those files without pointing to static directory addresses.

Application.StartupPath Property
Namespace: System.Windows.Forms

Application.StartupPath property gets the path for the executable file that started the application, not including the executable name.

Directory.SetCurrentDirectory Method
Sets the application's current working directory to the specified directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx

System.IO.Directory.GetCurrentDirectory()
A string containing the path of the current working directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx

Assembly.GetExecutingAssembly Method
Gets the assembly that contains the code that is currently executing.
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx

System.Reflection.Assembly.GetExecutingAssembly().Location
It returns the file name of the current binary

The following simple sample can show the result of aboved mentioned methods:

string dfltDir = @"C:\TEMP";
if( Directory.Exists( dfltDir ) )
Directory.SetCurrentDirectory( dfltDir );

StringBuilder sb = new StringBuilder();
sb.AppendLine("GetCurrentDirectory(): ");
sb.AppendLine( Directory.GetCurrentDirectory() );
sb.AppendLine();
sb.AppendLine( "Application.StartupPath: " );
sb.AppendLine( Application.StartupPath );
sb.AppendLine();
sb.AppendLine("Assembly.GetExecutingAssembly().Location: ");
sb.AppendLine( System.Reflection.Assembly.GetExecutingAssembly().Location);
sb.AppendLine();

MessageBox.Show(sb.ToString());

Share/Bookmark

No comments: