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

前端 未结 30 2793
小蘑菇
小蘑菇 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();
    
    0 讨论(0)
  • 2020-11-21 17:05

    I've defined the following property as we use this often in unit testing.

    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);
        }
    }
    

    The Assembly.Location property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use CodeBase which gives you the path in URI format, then UriBuild.UnescapeDataString removes the File:// at the beginning, and GetDirectoryName changes it to the normal windows format.

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

    The only solution that worked for me when using CodeBase and UNC Network shares was:

    System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
    

    It also works with normal URIs too.

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

    I believe this would work for any kind of application:

    AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory
    
    0 讨论(0)
  • 2020-11-21 17:09

    What about this:

    System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    
    0 讨论(0)
  • 2020-11-21 17:09

    I got the same behaviour in the NUnit in the past. By default NUnit copies your assembly into the temp directory. You can change this behaviour in the NUnit settings:

    Maybe TestDriven.NET and MbUnit GUI have the same settings.

    0 讨论(0)
提交回复
热议问题