In this article I will explain with an example, how to delete file from server after download is finished in ASP.Net using C# and VB.Net.
The File will be first written to the Response Stream and the Response will be flushed and the File will be deleted from the Server’s Folder (Directory) in ASP.Net using C# and VB.Net.
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net Button control.
<asp:Button Text="Download File" runat="server" OnClick="DownloadFile" />
 
 
Namespaces
You will need to import the following namespace.
C#
using System.IO;
 
VB.Net
Imports System.IO
 
 
Delete File from server after download is finished
The File is stored in a Folder (Directory) named Files within the Project Folder.
When the Download File Button is clicked, first the Content Type and the Header for the File are set and then the File is written to the Response Stream and then the Response is flushed.
Finally, the File is deleted from the Folder (Directory) and the Response is terminated.
C#
protected void DownloadFile(object sender, EventArgs e)
{
    //File to be downloaded.
    string fileName = "CustomerReport.pdf";
 
    //Path of the File to be downloaded.
    string filePath = Server.MapPath(string.Format("~/Files/{0}", fileName));
       
    //Content Type and Header.
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
 
    //Writing the File to Response Stream.
    Response.WriteFile(filePath);
       
    //Flushing the Response.
    Response.Flush();
 
    //Deleting the File and ending the Response.
    File.Delete(filePath);
    Response.End();
}
 
VB.Net
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
    'File to be downloaded.
    Dim fileName As String = "CustomerReport.pdf"
 
    'Path of the File to be downloaded.
    Dim filePath As String = Server.MapPath(String.Format("~/Files/{0}", fileName))
 
    'Content Type and Header.
    Response.ContentType = "application/pdf"
    Response.AppendHeader("Content-Disposition", ("attachment; filename=" + fileName))
 
    'Writing the File to Response Stream.
    Response.WriteFile(filePath)
 
    'Flushing the Response.
    Response.Flush()
 
    'Deleting the File and ending the Response.
    File.Delete(filePath)
    Response.End()
End Sub
 
 
Downloads