2010-11-05 78 views
3

在我的ASP.NET MVC應用程序中,我生成Excel報告,我有一個模板文件,我複製和更改。該模板文件放在我的解決方案中的文件夾中。我想用它如下:訪問ASP.NET MVC中的服務器上的文件

string templatePath = @"\Templates\report.xlsx"; 

using (var template = File.OpenRead(templatePath)) { 
    // Copy template and process content 
} 

但是這個代碼生成異常

Couldnot find a part of the path 'C:\Templates\report.xlsx'. 

我應該如何引用此文件?

我也使用

string templatePath = @"~\Templates\report.xlsx"; 

嘗試,但導致

Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Templates\report.xlsx'. 

它的工作但是當我使用絕對路徑,但是這是沒有意義的我的生產服務器。

+1

如果在路徑中使用代字號,則重要的是在字符串上調用「Server.MapPath」來解析它。 – Jess 2010-11-05 15:51:10

回答

8

我相信你會用普通的ASP.NET方式來做,假設Templates是你的web應用程序中的一個目錄。

string templatePath = @"~\Templates\report.xlsx"; 

using (var template = File.OpenRead(Server.MapPath(templatePath))) { 
    // Copy template and process content 
} 
+0

以這種方式嘗試它呢?Server.MapPath(「/ Templates/report.xlsx」)'...?等等......你剛剛刪除了你的評論,說它沒有用。做到了? – Charlino 2010-11-05 16:34:09

+0

起初我沒有很好地閱讀他的答案。他把它放在'File.OpenRead()'裏面。把這個聲明放在這個任務上是我認爲更清晰的代碼,但這是個人的風格。 – Jan 2010-11-06 12:08:06

0

您需要使用使用Server.Mappath(路徑)

string templatePath = Server.MapPath("~/Templates/report.xlsx"); //Note the forward slashes instead of backslashes. 

using (var template = File.OpenRead(templatePath)) { 
    // Copy template and process content 
} 

這將映射到服務器上的完整路徑虛擬目錄路徑。

+0

反斜槓爲我工作,你能解釋爲什麼斜線更好嗎? – Jan 2010-11-06 12:09:06

+0

猜猜我從來沒有用反斜槓試過它。反斜線通常表示實際的物理路徑,而正斜槓表示容納應用程序的虛擬目錄。 Server.MapPath()在同一臺服務器上創建一個虛擬目錄,並將其映射到完全合格的物理路徑。也許它足夠聰明,知道你打算做什麼,這就是反斜槓工作的原因。我不完全確定。 – Chev 2010-11-06 15:06:13

+0

我敢打賭,我知道它爲什麼有效。 Templates \ report.xlsx是您的根虛擬目錄的物理子目錄,因此它正在工作。但是,我敢打賭,如果Templates目錄只是根虛擬目錄的虛擬子目錄,並且物理目錄位於其他位置,則反斜槓將無法工作。我應該在某個時候測試一下。如果是這種情況,那麼我仍然會推薦使用正斜槓,以防萬一您需要移動目錄結構而讓您的虛擬目錄保持不變。 – Chev 2010-11-06 15:09:09

相關問題