开发者

Ubiquitous way to get the root directory an application is running in via C#

开发者 https://www.devze.com 2022-12-10 16:54 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消