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

前端 未结 30 2791
小蘑菇
小蘑菇 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:11

    How about this ...

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

    Then just hack off what you do not need

    0 讨论(0)
  • 2020-11-21 17:12

    Here is a VB.NET port of John Sibly's code. Visual Basic is not case sensitive, so a couple of his variable names were colliding with type names.

    Public Shared ReadOnly Property AssemblyDirectory() As String
        Get
            Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase
            Dim uriBuilder As New UriBuilder(codeBase)
            Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)
            Return Path.GetDirectoryName(assemblyPath)
        End Get
    End Property
    
    0 讨论(0)
  • 2020-11-21 17:13

    You will get incorrect directory if a path contains the '#' symbol. So I use a modification of the John Sibly answer that is combination UriBuilder.Path and UriBuilder.Fragment:

    public static string AssemblyDirectory
    {
        get
        {
            string codeBase = Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            //modification of the John Sibly answer    
            string path = Uri.UnescapeDataString(uri.Path.Replace("/", "\\") + 
              uri.Fragment.Replace("/", "\\"));
            return Path.GetDirectoryName(path);
         }
    }
    
    0 讨论(0)
  • 2020-11-21 17:14

    Starting with .net framework 4.6 / .net core 1.0, there is now a AppContext.BaseDirectory, which should give the same result as AppDomain.CurrentDomain.BaseDirectory, except that AppDomains were not part of the .net core 1.x /.net standard 1.x API.

    AppContext.BaseDirectory
    
    0 讨论(0)
  • 2020-11-21 17:14

    You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath

    0 讨论(0)
  • 2020-11-21 17:15
    string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);
    
    0 讨论(0)
提交回复
热议问题