C# 獲取當前執行DLL 所在路徑


有的時候,當前執行的DLL 和啟動的EXE 所在路徑並不一致,這時我們想要獲得當前執行DLL 所在路徑可以使用下面的方法。

// Summary:
// Gets the path or UNC location of the loaded file that contains the manifest.
//
// Returns:
// The location of the loaded file that contains the manifest. If the loaded file
// was shadow-copied, the location is that of the file after being shadow-copied.
// If the assembly is loaded from a byte array, such as when using the System.Reflection.Assembly.Load(System.Byte[])
// method overload, the value returned is an empty string ("").
//
// Exceptions:
// T:System.NotSupportedException:
// The current assembly is a dynamic assembly, represented by an System.Reflection.Emit.AssemblyBuilder
// object.

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 

  

// Summary:
// Gets the location of the assembly as specified originally, for example, in an
// System.Reflection.AssemblyName object.
//
// Returns:
// The location of the assembly as specified originally.

public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

 

通過 CodeBase 得到一個 URI 格式的路徑;
用 UriBuild.UnescapeDataString 去掉前綴 File://;
用 GetDirectoryName 把它變成正常的 windows 格式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM