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

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

    This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.

    I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName. Alas, the #if DEBUG. So if someone can improve that!

    Feel free to edit and improve.

    Getting app folder. Useful for web roots, unittests to get the folder of test files.

    public static string AppPath
    {
        get
        {
            DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
    
            while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                    || appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
            {
                appPath = appPath.Parent;
            }
            return appPath.FullName;
        }
    }
    

    Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.

    public static string BinPath
    {
        get
        {
            string binPath = AppDomain.CurrentDomain.BaseDirectory;
    
            if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                && !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
            {
                binPath = Path.Combine(binPath, "bin");
                //-- Please improve this if there is a better way
                //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
    #if DEBUG
                if (Directory.Exists(Path.Combine(binPath, "Debug"))) 
                            binPath = Path.Combine(binPath, "Debug");
    #else
                if (Directory.Exists(Path.Combine(binPath, "Release"))) 
                            binPath = Path.Combine(binPath, "Release");
    #endif
            }
                return binPath;
        }
    }
    

提交回复
热议问题