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

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

    I've been using Assembly.CodeBase instead of Location:

    Assembly a;
    a = Assembly.GetAssembly(typeof(DaoTests));
    string s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll
    Assert.AreEqual(true, s.StartsWith("FILE://"), "CodeBase is " + s);
    s = s.Substring(7, s.LastIndexOf('/') - 7); // 7 = "file://"
    while (s.StartsWith("/")) {
        s = s.Substring(1, s.Length - 1);
    }
    s = s.Replace("/", "\\");
    

    It's been working, but I'm no longer sure it is 100% correct. The page at http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx says:

    "The CodeBase is a URL to the place where the file was found, while the Location is the path where it was actually loaded. For example, if the assembly was downloaded from the internet, its CodeBase may start with "http://", but its Location may start with "C:\". If the file was shadow-copied, the Location would be the path to the copy of the file in the shadow copy dir. It’s also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC. Location will always be set for assemblies loaded from disk, however."

    You may want to use CodeBase instead of Location.

提交回复
热议问题