ASP.NET MVC3:无法查找/访问文件

时间:2012-02-07 14:27:45

标签: asp.net asp.net-mvc-3

 String DocLocation = System.AppDomain.CurrentDomain.BaseDirectory + "Files/test.pdf";
        // or
 String DocLocation = Url.Content("~/Files/test.pdf");

 var document = new FileStream(DocLocation, FileMode.Open);
 var mimeType = "application/pdf";
 var fileDownloadName = "download.pdf";

 return File(document, mimeType, fileDownloadName);

第一种方法是UnauthorizedAccessException。

第二种方法无法找到该文件。

我正在尝试发送文件进行下载。使用完整的桌面路径似乎有效。

另外,我如何在浏览器中显示PDF(注意,仍然需要下载选项,因为并非所有都是pdf)?

2 个答案:

答案 0 :(得分:4)

尝试Server.MapPath(“〜/ Files / test.pdf”)

答案 1 :(得分:2)

File()在磁盘上采用物理路径 因此,您无法使用Url.Content,因为它会返回浏览器的相对URL。

相反,您需要Server.MapPath,它将应用程序相对路径转换为本地磁盘上的完整路径。