2011-08-18 115 views
12

我有我的docx.xsl文件在我的項目/斌/調試folder.Now我想訪問這個文件,只要我需要。但我無法訪問此文件。如何訪問Visual studio 2010中項目文件夾中的bin/debug文件?

WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true); 
MainDocumentPart mainDocPart = wordDoc.MainDocumentPart; 
XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream()); 
XslCompiledTransform xslt = new XslCompiledTransform(); 

string xsltFile = @"\\docx.xsl"; // or @"docx.xsl"; 

xslt.Load(xsltFile); 
XmlTextWriter writer = new XmlTextWriter(outputFile, null); 
xslt.Transform(xpathDoc, null, writer); 
writer.Close(); 
wordDoc.Close(); 

請指導我把正確的有效路徑訪問docx.xsl文件...

+0

爲什麼不把文件嵌入到可執行文件中作爲資源呢?一個文件少部署,無路徑麻煩 – adrianm

+0

@Adrianm:我該怎麼做?你可以給我一個程序嗎? – Saravanan

+0

要在很多代碼放置評論,所以我添加了一個答案 – adrianm

回答

26

你可以決定你的可執行文件的位置,並假設該文件將與應用程序相關的部署目錄,那麼這應該可以幫助您查找文件中的調試和部署:

string executableLocation = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location); 
string xslLocation = Path.Combine(executableLocation, "docx.xsl"); 

您可能需要在你的文件的頂部輸入下面的命名空間:

using System; 
using System.IO; 
using System.Reflection; 
+0

錯誤消息:名稱大會不存在的上下文?..我如何把名字空間? – Saravanan

+0

讓我用相關的命名空間更新... –

+0

using System.Reflection;非常感謝 – Saravanan

1

Application.StartupPath爲您提供了bin/debug的完整路徑。

所以,你需要做的是:

string xsltFile =Application.StartupPath + @"\\docx.xsl"; 
+1

對不起,它沒有工作... – Saravanan

+0

正確的是:string xsltFile = Application.StartupPath + @「\\ docx.xsl」;非常感謝 – Saravanan

7

如果添加的文件作爲資源你不需要處理在運行時路徑。

  • 將文件添加到Visual Studio項目並將構建操作設置爲「Embedded Resource」。

資源的名稱是項目默認名稱空間+任何文件夾,就像項目中的任何代碼文件一樣。

string resourceName = "DefaultNamespace.Folder.docx.xsl"; 

如果在同一個文件夾中的代碼,你可以像這樣

string resourceName = string.Format("{0}.docx.xsl", this.GetType().Namespace); 
  • 然後你閱讀使用資源流Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)

在你的情況的文件,它看起來像這樣:

using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) 
using (var reader = XmlReader.Create(stream)) 
    xslt.Load(reader); 
+0

非常感謝adrianm – Saravanan

-1

爲了從Bin/Debug文件夾訪問文件,只需指定文件名。見下面

xslt.Load("docx.xsl"); 
相關問題