我有一個類庫正在讀取一些XSLT文件。我使用的是資源,但是它們已經在dll中預編譯,我們希望能夠隨時更改這些文件,所以我被要求從文件系統中讀取它們。如何從Web應用程序調用時獲取類庫的路徑?
我開始使用相對路徑,單元測試運行正常,但集成失敗,因爲在這種情況下,它們正在運行Web應用程序,並出現錯誤的路徑。
的代碼非常簡單,它只是加載XSLT:
string xslFilePath = @"xslts\transformation1.xsl";
XslCompiledTransform transformation = new XslCompiledTransform();
transformation.Load(xslFilePath, new XsltSettings(true, true), new XmlUrlResolver());
在集成測試的錯誤是:
DirectoryNotFoundException ExceptionMessage - 找不到路徑的一部分「C :\ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \ xslts \ transformation1.xsl'。
到目前爲止,我已經找到了最近的解決方案是:
string codeBase = Assembly.GetAssembly(typeof(Class1)).CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string fullPath = Uri.UnescapeDataString(uri.Path);
string theDirectory = Path.GetDirectoryName(fullPath);
string relativePath = @"\xslts\transformation1.xsl";
string path = theDirectory + relativePath;
但它檢索錯誤的道路,這一次它是一個的使用DLL中的Web應用程序的路徑。我仍然在努力尋找解決方案,它必須是一種獲取dll路徑的方法。
要讀取的文件的實際位置是什麼? – abatishchev 2011-05-20 09:19:49
假設位置爲:c:\ dll \ xslts \ file.xsl,並且該dll由位於c:\ webapplication中的Web應用程序使用。我開始認爲這是不可能的,我需要將這些xslts移動到Web應用程序目錄,但它對我來說沒有多大意義,因爲它們只能用於該dll。 – 2011-05-20 09:31:44
作爲參考添加的dll將被複制到\ bin。所以使用絕對路徑。或者將文件嵌入爲資源 – abatishchev 2011-05-20 09:38:41