有没有办法获取当前代码所在的程序集的路径? 我不但愿调用程序集的路径,而只是包含代码的路径。 web
基本上,个人单元测试须要读取一些相对于dll的xml测试文件。 我但愿该路径始终正确解析,而无论测试dll是从TestDriven.NET,MbUnit GUI仍是其余版本运行。 app
编辑 :人们彷佛误解了我在问什么。 webapp
个人测试库位于 单元测试
C:\\ projects \\ myapplication \\ daotests \\ bin \\ Debug \\ daotests.dll 测试
我想走这条路: ui
C:\\ projects \\ myapplication \\ daotests \\ bin \\ Debug \\ this
当我从MbUnit Gui运行时,到目前为止,这三个建议使我失望: spa
Environment.CurrentDirectory
给出c:\\ Program Files \\ MbUnit debug
System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location
给出C:\\ Documents and Settings \\ george \\ Local Settings \\ Temp \\ .... \\ DaoTests.dll code
System.Reflection.Assembly.GetExecutingAssembly().Location
与上一个相同。
这应该工做:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); Assembly asm = Assembly.GetCallingAssembly(); String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath); string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");
我正在使用它来部署DLL文件库以及一些配置文件(这是从DLL文件中使用log4net)。
这就是我想出的。 在Web项目之间,进行单元测试(nunit和resharper测试运行程序) ; 我发现这对我有用。
我一直在寻找代码来检测内部版本的配置, Debug/Release/CustomName
。 las, #if DEBUG
。 所以,若是有人能够改善它 !
随时进行编辑和改进。
正在获取应用程序文件夹 。 对于Web根目录颇有用,unittests用于获取测试文件的文件夹。
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; } }
获取bin文件夹 :对于使用反射执行程序集颇有用。 若是因为构建属性而将文件复制到那里。
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; } }
据我所知,大多数其余答案都有一些问题。
对于基于磁盘(而不是基于Web的),非GACed程序集 ,执行此操做的正确方法是使用当前正在执行的程序集的CodeBase
属性。
这将返回一个URL( file://
)。 不用搞乱字符串操做或UnescapeDataString
,能够利用Uri
的LocalPath
属性以最小的麻烦进行转换。
var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase; var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath; var directoryPath = Path.GetDirectoryName(filePathToCodeBase);
Web应用程序?
Server.MapPath("~/MyDir/MyFile.ext")
与John的答案相同,但扩展方法略为冗长。
public static string GetDirectoryPath(this Assembly assembly) { string filePath = new Uri(assembly.CodeBase).LocalPath; return Path.GetDirectoryName(filePath); }
如今您能够执行如下操做:
var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();
或者,若是您喜欢:
var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();