CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

File Download in ASP.Net with C#
Submitted By Bala Murugan
On 11/22/2008 5:08:41 AM
Tags: ASP.Net,C#,CodeDigest  

File Download in ASP.Net with C#

Sometimes, we may need a feature where we need to read a file content on  the server and render it back to the user as a file download. You can make a file donwloaded by using a simple hyperlink but the disadvantages are the path of the file will be visible. This also prevents the search engines from indexing your files that are downloadable.

 

In  the below code, we will read the file as byte array and will render it back to the requested user by setting the response content type as application/octet-stream. This code once executed will enable a download dialog box with Open, Save options.

 

private void btnDownload_Click(object sender, System.EventArgs e)
{
// The file path to download.

string filepath = @"C:\shadow_copy.rar";

// The file name used to save the file to the client's system..

string filename = Path.GetFileName( filepath );
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream( filepath, System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read );
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader( "Content-Disposition", "attachment; filename=" + filename );
// Read the bytes from the stream in small portions.
while ( bytesToRead > 0 )
{
// Make sure the client is still connected.
if ( Response.IsClientConnected )
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read( buffer, 0, 10000 );
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if ( stream != null ) {
stream.Close();
}
}
}

 

As you can see in the above code, the original file path will be hidden to the requesting user.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..