访问路径Server.MapPath被拒绝

时间:2012-09-21 08:50:23

标签: c# asp.net download

我创建了一个pdf文档

        var document = new Document();
        string path = Server.MapPath("AttachementToMail");
        PdfWriter.GetInstance(document, new FileStream(path + 
                  "/"+DateTime.Now.ToShortDateString()+".pdf", FileMode.Create));

现在我想下载这个文件

 Response.ContentType = "Application/pdf";
 Response.AppendHeader("Content-Disposition", "attachment; filename="+   
                                DateTime.Now.ToShortDateString() + ".pdf" + "");
 Response.TransmitFile(path);
 Response.End();

但它给了我错误 拒绝访问路径'〜\ AttachementToMail'。

IIS_IUSRS的读/写访问权限

1 个答案:

答案 0 :(得分:2)

您提供写入的路径是虚拟路径。 TransmitFile期望绝对路径。

您的代码应如下所示:

var document = new Document();
string path = Server.MapPath("AttachementToMail");
var fileName =  DateTime.Now.ToString("yyyyMMdd")+".pdf";
var fullPath = path + "\\" + fileName;

//Write it to disk
PdfWriter.GetInstance(document, new FileStream(fullPath, FileMode.Create));

//Send it to output
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename="+ fileName );

Response.TransmitFile(fullPath);
Response.Flush();
Response.End();

DateTime.Now代表当前时间。将它用作文件名时要小心。 使用ToShortDateString有点风险,因为有些文化将/置于该格式中。无论服务器文化如何,使用ToString都可以修复文件名格式。