ASP.Net – How to delete file from server after download is finished

Posted: April 30, 2011 in ASP.NET
Tags: ,

Here I am providing the code snippet that will allow us to delete the file once the file is downloaded on the client’s machine. Below are the code snippets

C#

private void DownloadFile()
{
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition","attachment; filename=myFile.txt");
Response.WriteFile(Server.MapPath("~/uploads/myFile.txt"));
Response.Flush();
System.IO.File.Delete(Server.MapPath("~/uploads/myFile.txt"));
Response.End();
}

VB.Net


Private Sub DownloadFile()
Response.ContentType = ContentType
Response.AppendHeader("Content-Disposition", "attachment; filename=myFile.txt")
Response.WriteFile(Server.MapPath("~/uploads/myFile.txt"))
Response.Flush()
System.IO.File.Delete(Server.MapPath("~/uploads/myFile.txt"))
Response.End()
End Sub

Advertisements
Comments
  1. lukasz says:

    Thanks for this post!

    But don’t you miss something in the first line?
    What is the ContentType?

    >Response.ContentType = ContentType;

  2. johny says:

    this function delete the file even before downloading,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s