有沒有辦法獲取當前代碼所在的程序集的路徑? 我不但願調用程序集的路徑,而只是包含代碼的路徑。 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();