2010-11-05 76 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

相关问题