How do I get the path of the assembly the code is in?

前端 未结 30 2759
小蘑菇
小蘑菇 2020-11-21 16:17

Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.

<
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 17:00

    Same as John's answer, but a slightly less verbose extension method.

    public static string GetDirectoryPath(this Assembly assembly)
    {
        string filePath = new Uri(assembly.CodeBase).LocalPath;
        return Path.GetDirectoryName(filePath);            
    }
    

    Now you can do:

    var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();
    

    or if you prefer:

    var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();
    

提交回复
热议问题