How to get Directory while running unit test

后端 未结 14 874
余生分开走
余生分开走 2021-02-02 05:07

Hi when running my unit test I\'m wanting to get the directory my project is running in to retrieve a file.

Say I have a Test project named MyProject. Test I run:

<
14条回答
  •  一个人的身影
    2021-02-02 05:20

    use StackTrace

        internal static class Extensions
        {
            public static string GetSourceDirectoryName(this Type type)
            {
                StackTrace stackTrace = new StackTrace(true);
    
                foreach (var frame in stackTrace.GetFrames())
                {
                    if (frame.GetMethod() is { } method && method.DeclaringType == type)
                    {
                        return Path.GetDirectoryName(frame.GetFileName());
                    }
                }
    
                throw new Exception($"未找到{type.Name}源文件目录");
            }
        }
    
    

提交回复
热议问题