簡體   English   中英

確定應用程序根目錄的最佳方法是什么?

[英]What is the best way to determine application root directory?

我需要在我的應用程序根目錄中獲取所有dll。 最好的方法是什么?

string root = Application.StartupPath;

要么,

string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName;

在那之后,

Directory.GetFiles(root, "*.dll");

哪種方式更好? 還有更好的方法嗎?

AppDomain.CurrentDomain.BaseDirectory是我這樣做的方式。

然而:

Application.StartupPath獲取可執行文件的目錄

AppDomain.BaseDirectory獲取用於解析程序集的目錄

由於它們可能不同,您可能希望使用Application.StartupPath,除非您關心程序集解析。

這取決於。 如果您想要啟動應用程序的EXE目錄,那么您的兩個示例中的任何一個都可以使用。 但請記住,.NET非常靈活,可能是另一個應用程序鏈接到您的EXE並且正在調用它,可能來自另一個目錄。

這種情況不會經常發生,如果有的話,你可能會寫,但這是可能的。 因此,我更喜歡指定我感興趣的程序集並從中獲取目錄。 然后我知道我將所有DLL都放在與特定程序集相同的目錄中。 例如,如果您的應用程序MyApp.exe中有一個類MyApp.MyClass,那么您可以這樣做;

string root = string.Empty;
Assembly ass = Assembly.GetAssembly( typeof( MyApp.MyClass ) );
if ( ass != null )
{
   root = ass.Location;
}

這是一個老問題,但我總是習慣使用:

Environment.CurrentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

但是,看看這里的解決方案,我認為需要做一些簡單的測試:

var r = new List<long>();
var s = Stopwatch.StartNew();

s.Restart();
string root1 = Application.StartupPath;
r.Add(s.ElapsedTicks);

s.Restart();
string root2 = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
r.Add(s.ElapsedTicks);

s.Restart();
string root3 = Path.GetDirectoryName(new FileInfo(Assembly.GetExecutingAssembly().Location).FullName);
r.Add(s.ElapsedTicks);

s.Restart();
string root4 = AppDomain.CurrentDomain.BaseDirectory;
r.Add(s.ElapsedTicks);

s.Restart();
string root5 = Path.GetDirectoryName(Assembly.GetAssembly( typeof( Form1 ) ).Location);
r.Add(s.ElapsedTicks);

滴答結果如下:

  • 49
  • 306
  • 166
  • 26
  • 201

所以似乎AppDomain.CurrentDomain.BaseDirectory是要走的路。

如果要獲取應用程序根文件夾路徑,請使用下面的代碼示例。

string path =new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName

我用

Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath)

如果使用卷影復制,Assembly.Location將指向卷影副本,因此使用CodeBase是更好的選擇,但CodeBase是一個Url。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM