Sunday, June 18, 2006

Tracking file download

We usually put a hyperlink to download a file. But the following code helps to track the download. We can check whether the user has successfully downloaded the file or not. This can be used in juke box or movie download sites to prevent multiple downloads.

private void DownloadFile(string strfile)
{
System.IO.Stream iStream = null;
byte[] buffer = new Byte[1000];
int length;
long dataToRead=-1;

bool startstatus=false;
string filepath = strfile;
string filename = System.IO.Path.GetFileName(filepath);

try
{
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;

Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 1000);

// Write the data to the current output
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();
buffer= new Byte[1000];
dataToRead = dataToRead - length;

if(startstatus == false)
{
// Started downloading

startstatus=true;
}

}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
// disconnected or unable to download
}
}
}
catch (Exception ex)
{
dataToRead = -1;
}
finally
{
try
{
if(dataToRead == -1)
{
// disconnected or unable to download
}
else
{
// file successfully downloaded
}
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
catch(Exception ex)
{

}
}
}

1 comment:

Senthil kumar T said...

Really good..........