Ubiquitous way to get the root directory an application is running in via C#
My application requires that I have access to the file syste开发者_高级运维m. Regardless if the code runs on a web server or a console app, how can I get the root directory the application is running in. Something like C:\TheApplication...
Thanks!
Easiest is probably:
System.Reflection.Assembly.GetExecutingAssembly().Location
Hope this helps,
-Oisin
You can try this:
String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
You can read more about the two classes here:
- Assembly class
- Path class
I just tested out a very basic way to do this that works in both asp.net and within a windows service.
var binariesPath = string.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath)
? AppDomain.CurrentDomain.BaseDirectory // Windows Service
: AppDomain.CurrentDomain.RelativeSearchPath; // Asp.net
Even easier:
string myPath = Application.ExecutablePath;
For winforms application, this is always set.
精彩评论