Access to the path Server.MapPath is denied

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 02:53:47

问题


I created one pdf document

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

Now I want to download this document

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

but it gave me error Access to the path '~\AttachementToMail' is denied.

read / write access for IIS_IUSRS exists


回答1:


The path you are providing to write is a virtual path. TransmitFile expects an absolute path.

Your code should look something like this:

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 represents the current time. Be careful when you use it as the file name. Using ToShortDateString is a little risky, as some cultures put / in that format. Using ToString will allow you to fix your filename format regardless of the server culture.



来源:https://stackoverflow.com/questions/12527210/access-to-the-path-server-mappath-is-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!