Overview Sometimes i have to read/write files from the root directory of my application. Usually i did this with Environment.CurrentDirectory . Unfortunately, this only works if the application is a standalone application(.exe). In case the application is a windows service or a asp.net website, the path from Environment.CurrentDirectory is wrong.
There are several ways to get the root directory of an application, but so far i found only one which works in all scenarios. The only one which always works is:
1 2 System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)
Here is a (incomplete) list of ways to get the root path of a c# application:
Windows service 1 2 3 4 5 6 7 8 Environment.CurrentDirectory: System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath) AppDomain.CurrentDomain.BaseDirectory: Process.GetCurrentProcess().MainModule.FileName.Substring(0 , Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //D:\project\WindowsServiceTest\WindowsServiceTest\bin\Debug`
Console application 1 2 3 4 5 6 7 8 Environment.CurrentDirectory: System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): AppDomain.CurrentDomain.BaseDirectory: Process.GetCurrentProcess().MainModule.FileName.Substring(0 , Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //D:\project\ConsoleApplication3\ConsoleApplication3\bin\Debug
asp.net mvc3 website vs2010 integrated webserver (Debug mode) 1 2 3 4 5 6 7 8 Environment.CurrentDirectory: System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): AppDomain.CurrentDomain.BaseDirectory: Process.GetCurrentProcess().MainModule.FileName.Substring(0 , Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0
asp.net mvc3 website IIS (Release mode) 1 2 3 4 5 6 7 8 Environment.CurrentDirectory: System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): AppDomain.CurrentDomain.BaseDirectory: Process.GetCurrentProcess().MainModule.FileName.Substring(0 , Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //c:\windows\system32\inetsrv