2010-07-17 65 views
5

我知道在執行代碼的同一個目錄中有一些文件位於其中。我需要找到他們,並通過另一種方法:獲取執行代碼所在的目錄

MyLib.dll 
Target1.dll 
Target2.dll 

Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" }); 

所以我打電話System.IO.Directory.GetFiles(path, "*.dll")。但現在我需要知道的路徑:

string path = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName) 

但有更多的短路?

+0

[This post](http://stackoverflow.com/questions/3163495/better-way-to-get-the-base-directory)應該給你幾個選項 – mhenrixon 2010-07-17 11:47:36

回答

6

您可以嘗試Environment.CurrentDirectory屬性。請注意,根據應用程序的類型(控制檯,WinForms,ASP.NET,Windows Service,...)及其運行方式,這可能會有所不同。

+0

我正在運行NUnit測試。在現實世界中,我稱'Foo(Server.MapPath(「〜/ bin」))'但在測試中,我只是想掃描包含測試的程序集根目錄 – abatishchev 2010-07-17 11:48:54

+0

謝謝! 'Environment.CurrentDirectory'就是我一直在尋找的東西。我的電話會從Temp返回一些內容,但您的 - 我正是需要的。 – abatishchev 2010-07-17 12:01:20

+1

Environment.CurrentDirectory在任何時候都不能按預期工作。如果您的應用程序訪問標準的Windows文件打開對話框,並且您選擇了一些路徑,那麼下一次調用Environment.CurrentDirectory將返回文件打開對話框中最後選擇的路徑,而不是執行程序的路徑。 – 10100111001 2014-04-30 07:42:52

2

Environment.CurrentDirectory返回當前目錄,而不是執行代碼所在的目錄。如果使用Directory.SetCurrentDirectory,或者如果使用設置目錄的快捷方式啓動程序,則該目錄不會是您正在查找的目錄。

堅持原來的解決方案。使用屬性隱藏實現(並使其更短):

private DirectoryInfo ExecutingFolder 
{ 
    get 
    { 
     return new DirectoryInfo (
      System.IO.Path.GetDirectoryName (
       System.Reflection.Assembly.GetExecutingAssembly().Location)); 
    } 
}