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

前端 未结 30 3160
小蘑菇
小蘑菇 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条回答
  •  萌比男神i
    2020-11-21 16:58

    In all these years, nobody has actually mentioned this one. A trick I learned from the awesome ApprovalTests project. The trick is that you use the debugging information in the assembly to find the original directory.

    This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.

    But this will get you paths that are relative to the location of the source code file you call it from

    public static class PathUtilities
    {
        public static string GetAdjacentFile(string relativePath)
        {
            return GetDirectoryForCaller(1) + relativePath;
        }
        public static string GetDirectoryForCaller()
        {
            return GetDirectoryForCaller(1);
        }
    
    
        public static string GetDirectoryForCaller(int callerStackDepth)
        {
            var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);
            return GetDirectoryForStackFrame(stackFrame);
        }
    
        public static string GetDirectoryForStackFrame(StackFrame stackFrame)
        {
            return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;
        }
    }
    

提交回复
热议问题