簡體   English   中英

獲取執行代碼所在的目錄

[英]Get directory where executed code is located

我知道在我的代碼執行的同一目錄中有一些文件。 我需要找到它們並傳遞給另一種方法:

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)

但還有更短的路嗎?

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

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

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

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

暫無
暫無

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

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