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

前端 未结 30 2792
小蘑菇
小蘑菇 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 16:52
    AppDomain.CurrentDomain.BaseDirectory
    

    works with MbUnit GUI.

    0 讨论(0)
  • 2020-11-21 16:52

    This should work:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    Assembly asm = Assembly.GetCallingAssembly();
    String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);
    
    string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");
    

    I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).

    0 讨论(0)
  • 2020-11-21 16:52

    Web application?

    Server.MapPath("~/MyDir/MyFile.ext")
    
    0 讨论(0)
  • 2020-11-21 16:54

    As far as I can tell, most of the other answers have a few problems.

    The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase property.

    This returns a URL (file://). Instead of messing around with string manipulation or UnescapeDataString, this can be converted with minimal fuss by leveraging the LocalPath property of Uri.

    var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
    var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
    var directoryPath = Path.GetDirectoryName(filePathToCodeBase);
    
    0 讨论(0)
  • 2020-11-21 16:55

    Does this help?

    //get the full location of the assembly with DaoTests in it
    string fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;
    
    //get the folder that's in
    string theDirectory = Path.GetDirectoryName( fullPath );
    
    0 讨论(0)
  • 2020-11-21 16:56

    It's as simple as this:

    var dir = AppDomain.CurrentDomain.BaseDirectory;
    
    0 讨论(0)
提交回复
热议问题