Click here to Skip to main content
11,429,382 members (66,545 online)
Click here to Skip to main content

File Download in ASP.NET and Tracking the Status of Success/Failure of Download

, 27 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
File download in ASP.NET and tracking the status of success/failure of download

Introduction

This article demonstrates how to provide download of a file in ASP.NET along with tracking its success and failure. It will be useful especially in an e-commerce system that offers downloadable product option. In an e-commerce system, it is very important to keep track of status of download. For a download option, there can be two scenarios:

  1. Complete/success download
  2. Failure download

In an e-commerce system, the user may have a limited number of downloads allowed which is one in most of the cases. If a download is successful, it should update the record which will indicate to the user that he has already downloaded the file or increment the download count by 1. But for failure download, the user should be able to download it again or the download count should remain the same. So this article will help in tracking such status of download.

While working on an e-commerce project, I had a requirement to implement such a functionality where the success/failure of the download can be tracked. After searching for the solution, I found that there is no such article related to a similar problem. Then I came up with this solution after reading an article on transferring file in small packets. I hope this solution will help others struggling with a similar problem.

Background

When the function provided is called on the click of a download button, a similar window as shown below opens asking the user to Open, Save or Cancel.

Download_Track

Clicking Open or Save will result in start of download whereas Cancel will stop/fail the download.

Download_Track2.jpg

A user can Cancel the Download even after Open or Save click, which needs to be tracked.

Using the Code

The code contains the basic logic of File Download in ASP.NET, which will not give end-user any hint of the location of the file. First we create System.IO.FileInfo object providing the complete file path, which will give us the file length. We also create a FileStream object which will be passed to BinaryReader object which in turn will help reading the data into bytes. Then we use the Response object to transfer the data.

//File Path and File Name
string filePath = Server.MapPath("~/ApplicationData/DownloadableProducts");
string _DownloadableProductFileName = "DownloadableProduct_FileName.pdf";

System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + 
	_DownloadableProductFileName);
FileStream myFile = new FileStream(filePath + "\\" + 
	_DownloadableProductFileName, FileMode.Open, 
	FileAccess.Read, FileShare.ReadWrite);

//Reads file as binary values
BinaryReader _BinaryReader = new BinaryReader(myFile);

long startBytes = 0;
string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
string _EncodedData = HttpUtility.UrlEncode
	(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp; 

//Clear the content of the response
Response.Clear();
Response.Buffer = false;
Response.AddHeader("Accept-Ranges", "bytes");
Response.AppendHeader("ETag", "\"" + _EncodedData +"\"");
Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);

//Set the ContentType
Response.ContentType = "application/octet-stream";

//Add the file name and attachment, 
//which will force the open/cancel/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment;filename="+ FileName.Name);

//Add the file size into the response header
Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");

//Set the Content Encoding type
Response.ContentEncoding = Encoding.UTF8; 

//Send data
_BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);

There is no response coming back from the download window whether download is completed or aborted in between, so it becomes more difficult to know the status of download. The basic logic behind tracking the download status is transferring the file into smaller packets(size of packets can be kept as per convenience) and checking whether all the packets have been transferred. If there will be any failure in between the transfer of file, the total number of packets will be compared with the number of packets transferred. This comparison will decide the status (Success/Failure) of download. For a very small file, it is difficult to track failure of download as the number of packets will be very few. So more effective tracking will happen if the file size will be greater than 10 KB.

In the below code, we are getting the total number of packets by dividing the total bytes of data by 1024 to keep the packet size as 1 KB. To send the data packets one by one, we are using for loop. Using Response.BinaryWrite, we are sending the 1024 bytes of data at a time which is read using BinaryReader.

//Dividing the data in 1024 bytes package
int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024); 
//Download in block of 1024 bytes
int i;
for(i=0; i < maxCount && Response.IsClientConnected; i++)
{
    Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
    Respons.Flush(); 
}

Then we compare the number of data packets transferred with the total number of data packets which we calculated by dividing file length by 1024. If both the parameters are equal, that means that file transfer is successful and all the packets got transferred. If number of data packets transferred are less than the total number of data packets, that indicates there is some problem and the transfer was not complete.

//compare packets transferred with total number of packets
if (i < maxCount) return false;
return true;  

Close the Binary reader and File stream in final block.

//Close Binary reader and File stream
_BinaryReader.Close();
myFile.Close(); 

History

  • 27th April, 2010: Initial post

About Proteans Software Solutions

Proteans Software Solutions is an outsourcing company focusing on software product development and business application development on Microsoft Technology Platform. Committed to consistently deliver high-quality software products and services through continual improvement of our knowledge and practices focused on increased customer satisfaction.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anil Meharia
Software Developer Proteans Software Solutions Pvt. Ltd.
India India
I am working as a software engineer in Proteans Software Solutions.

Comments and Discussions

 
QuestionMessage Removed Pin
Member 1156931831-Mar-15 3:17
memberMember 1156931831-Mar-15 3:17 
Suggestionare you mad this was not working, next time check code and after that post any article . you r wasting my time Pin
arav98920-Aug-14 21:10
memberarav98920-Aug-14 21:10 
Questionfor-loop finishes to quick Pin
basb8220-Aug-14 4:34
memberbasb8220-Aug-14 4:34 
QuestionWhere should this function be called? Pin
SharePoint Specialist4-Oct-13 6:17
memberSharePoint Specialist4-Oct-13 6:17 
Questionaccident Pin
DanaTA19-Mar-13 19:51
memberDanaTA19-Mar-13 19:51 
Questionupdating record part Pin
DanaTA19-Mar-13 19:50
memberDanaTA19-Mar-13 19:50 
Question90% Downloaded File Pin
sachin.munot30-Jan-13 0:52
membersachin.munot30-Jan-13 0:52 
GeneralMy vote of 4 Pin
csharpbd13-Nov-12 1:24
membercsharpbd13-Nov-12 1:24 
GeneralMy vote of 4 Pin
thawait.himanshu17-May-12 8:00
memberthawait.himanshu17-May-12 8:00 
GeneralMy vote of 1 Pin
MD Navaid9-Apr-12 1:37
memberMD Navaid9-Apr-12 1:37 
QuestionWindows 7 Problem Pin
RaguvaranTS27-Feb-12 19:29
memberRaguvaranTS27-Feb-12 19:29 
QuestionHttpContext.Current.ApplicationInstance.CompleteRequest() should be used instead of Response.End() Pin
Muzaffar Ali Rana16-Feb-12 7:56
memberMuzaffar Ali Rana16-Feb-12 7:56 
AnswerRe: HttpContext.Current.ApplicationInstance.CompleteRequest() should be used instead of Response.End() Pin
DanaTA19-Mar-13 20:01
memberDanaTA19-Mar-13 20:01 
AnswerRe: HttpContext.Current.ApplicationInstance.CompleteRequest() should be used instead of Response.End() Pin
DanaTA21-Mar-13 21:14
memberDanaTA21-Mar-13 21:14 
GeneralMy vote of 3 Pin
Muzaffar Ali Rana16-Feb-12 7:50
memberMuzaffar Ali Rana16-Feb-12 7:50 
QuestionWorking with smaller files #Possible Solution Pin
Juan Steyn14-Feb-12 23:40
memberJuan Steyn14-Feb-12 23:40 
GeneralMy vote of 1 Pin
Jakkamnaresh25-Jan-12 3:11
memberJakkamnaresh25-Jan-12 3:11 
QuestionCannot view dialog box when working with mster page Pin
Member 782360223-Aug-11 22:34
memberMember 782360223-Aug-11 22:34 
GeneralHey some doubt Pin
Navnath_Kale31-Jan-11 6:53
memberNavnath_Kale31-Jan-11 6:53 
GeneralRe: Hey some doubt Pin
ycg16691126-Sep-11 0:22
memberycg16691126-Sep-11 0:22 
哈哈,认识Chinese吗?
GeneralGood one Pin
thatraja30-Nov-10 3:54
memberthatraja30-Nov-10 3:54 
AnswerDownLoad Count is not correct Pin
zhongweis22-Oct-10 21:21
memberzhongweis22-Oct-10 21:21 
GeneralRe: DownLoad Count is not correct Pin
dbassett7423-May-11 8:58
memberdbassett7423-May-11 8:58 
GeneralFile not available on same server Pin
mohitscjain1-Oct-10 3:48
membermohitscjain1-Oct-10 3:48 
GeneralBetter Path.Combine Pin
rh_24-Sep-10 1:35
memberrh_24-Sep-10 1:35 
GeneralRe: Better Path.Combine Pin
Anil Meharia24-Sep-10 1:56
memberAnil Meharia24-Sep-10 1:56 
Questionhow to get the client saving path ? Pin
ab_dc26-Jun-10 10:12
memberab_dc26-Jun-10 10:12 
AnswerRe: how to get the client saving path ? Pin
Anil Meharia26-Jun-10 19:51
memberAnil Meharia26-Jun-10 19:51 
GeneralRe: how to get the client saving path ? Pin
ab_dc26-Jun-10 22:32
memberab_dc26-Jun-10 22:32 
GeneralRe: how to get the client saving path ? Pin
Anil Meharia27-Jun-10 21:29
memberAnil Meharia27-Jun-10 21:29 
GeneralNice Pin
Xmen W.K.10-May-10 18:56
memberXmen W.K.10-May-10 18:56 
GeneralGood job Anil.... Pin
vaibhavRakhe9-May-10 20:32
membervaibhavRakhe9-May-10 20:32 
NewsResume Download for Huge Files Pin
Norbert Bietsch2-May-10 2:02
memberNorbert Bietsch2-May-10 2:02 
GeneralRe: Resume Download for Huge Files Pin
Anil Meharia2-May-10 9:18
memberAnil Meharia2-May-10 9:18 
GeneralAwesome work man, I was in need of such solution. Pin
shriti.nisha@gmail.com29-Apr-10 8:49
membershriti.nisha@gmail.com29-Apr-10 8:49 
GeneralRe: Awesome work man, I was in need of such solution. Pin
Anil Meharia29-Apr-10 9:09
memberAnil Meharia29-Apr-10 9:09 
GeneralGreat one Pin
Brij28-Apr-10 20:06
mentorBrij28-Apr-10 20:06 
GeneralGood Article dude Pin
avi5128-Apr-10 2:44
memberavi5128-Apr-10 2:44 
JokeWorking Hard Pin
pun2et28-Apr-10 1:01
memberpun2et28-Apr-10 1:01 
Questionwhat about downloadmanagers? Pin
Basel Nimer28-Apr-10 0:28
memberBasel Nimer28-Apr-10 0:28 
AnswerRe: what about downloadmanagers? Pin
Anil Meharia28-Apr-10 0:33
memberAnil Meharia28-Apr-10 0:33 
GeneralRe: what about downloadmanagers? Pin
Pete O'Hanlon28-Apr-10 11:19
mvpPete O'Hanlon28-Apr-10 11:19 
GeneralGood job Anil.. Pin
SureshGubba27-Apr-10 22:08
memberSureshGubba27-Apr-10 22:08 
GeneralGood one -- Its nice way to keep track the status of download .. User friendly :) Pin
san_vetakari27-Apr-10 21:51
membersan_vetakari27-Apr-10 21:51 
General[My vote of 1] Question Pin
sasha winston27-Apr-10 6:40
membersasha winston27-Apr-10 6:40 
GeneralRe: [My vote of 1] Question Pin
Diamonddrake27-Apr-10 11:26
memberDiamonddrake27-Apr-10 11:26 
GeneralRe: [My vote of 1] Question Pin
Anil Meharia27-Apr-10 19:30
memberAnil Meharia27-Apr-10 19:30 
GeneralRe: [My vote of 1] Question Pin
Pete O'Hanlon28-Apr-10 11:18
mvpPete O'Hanlon28-Apr-10 11:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 27 Apr 2010
Article Copyright 2010 by Anil Meharia
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid