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

前端 未结 30 2800
小蘑菇
小蘑菇 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: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);
         }
    }
    

提交回复
热议问题