None
None

Reputation: 5670

System.IO.File.Delete() not working

My code is like this

 public static void Deleter()
 {
     HttpContext.Current.Response.Clear();
     HttpContext.Current.Response.ContentType = "application/pdf";
     HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "name" + ".pdf");
     HttpContext.Current.Response.TransmitFile("~/media/pdf/" + "name" + ".pdf");


     if (FileExists("/media/pdf/" + "name" + ".pdf"))
     {
         System.IO.File.Delete("D:/Projects/09-05-2013/httpdocs/media/pdf" + "name" + ".pdf");
     }
     HttpContext.Current.Response.End();

 }

after executing this entire code I still can see name.pdf in the folder.No error is thrown.can any one tell me whats going wrong?

Upvotes: 0

Views: 6662

Answers (2)

Habib
Habib

Reputation: 223277

Your concatenated path would result in a wrong address, use Path.Combine to combine two paths. Current it would be:

D:/Projects/09-05-2013/httpdocs/media/pdfname.pdf
                                     ^^^^^^
                                    //Missing slash. 

instead use:

System.IO.File.Delete(Path.Combine("D:/Projects/09-05-2013/httpdocs/media/pdf" 
                              , "name"+ ".pdf"));

Or if you want to use string concatenation then add a forward slash at the end of first string like:

System.IO.File.Delete("D:/Projects/09-05-2013/httpdocs/media/pdf/" + "name" + ".pdf");

Also consider using Server.MapPath instead of absolute path.

Upvotes: 2

Heinzi
Heinzi

Reputation: 172280

The string concatenation

"D:/Projects/09-05-2013/httpdocs/media/pdf" + "name" + ".pdf"

yields

D:/Projects/09-05-2013/httpdocs/media/pdfname.pdf

which is the file you delete, and which is not the same as

D:/Projects/09-05-2013/httpdocs/media/pdf/name.pdf

Upvotes: 3

Related Questions