Bazen uygulamalarımızın geçerli dizinini alıp dosya yazdırma veya okuma gibi işlemleri gerçekleştirme ihtiyacı duyarız fakat geçerli uygulama dizinini almak için birden fazla yöntem olduğundan en doğru olanını kullanmak daha sağlıklı olacaktır.
C# ile uygulamaların geçerli dizinini alma
Her c# uygulamasında geçerliliği doğru olarak bilinen ama yanlış olan bir durum var oda Environment.CurrentDirectory özelliğidir bu özellik sadece .exe’li projelerinizde kullanılabilmektedir windows service ve asp.net website projelerinizde doğru sonucu vermeyebilir.
Şimdi Windows service, Console application, asp.net mvc3 vs2010 debug mode ve asp.net mvc3 website IIS release mode’da hangi kullanım ne gibi sonuçlar ortaya koyuyor beraber görelim.
Windows Service
1 2 3 4 5 6 7 8 | Environment.CurrentDirectory: //C:Windowssystem32 System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath) //D:projectWindowsServiceTestWindowsServiceTestbinDebug AppDomain.CurrentDomain.BaseDirectory: //D:projectWindowsServiceTestWindowsServiceTestbinDebug Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //D:projectWindowsServiceTestWindowsServiceTestbinDebug |
Console Application
1 2 3 4 5 6 7 8 | Environment.CurrentDirectory: //D:projectConsoleApplication3ConsoleApplication3binDebug System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): //D:projectConsoleApplication3ConsoleApplication3binDebug AppDomain.CurrentDomain.BaseDirectory: //D:projectConsoleApplication3ConsoleApplication3binDebug Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //D:projectConsoleApplication3ConsoleApplication3binDebug |
Asp.net MVC3 VS2010 Web Projesi(Debug mode)
1 2 3 4 5 6 7 8 | Environment.CurrentDirectory: //C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0 System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): //D:projectMvcApplication1MvcApplication1bin AppDomain.CurrentDomain.BaseDirectory: //D:projectMvcApplication1MvcApplication1 Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //C:Program Files (x86)Common FilesMicrosoft SharedDevServer10.0 |
Asp.net MVC3 Website IIS (Release mode)
1 2 3 4 5 6 7 8 | Environment.CurrentDirectory: //c:windowssystem32inetsrv System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): //d:projectMvcApplication1MvcApplication1bin AppDomain.CurrentDomain.BaseDirectory: //d:projectMvcApplication1MvcApplication1 Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //c:windowssystem32inetsrv |