Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to download file and photo in C# Dot Net when we click on download button ?
Posted
Comments
Prerak Patel 19-Sep-11 4:39am    
If you click on download, it will download the file. Please rephrase your question. Are you trying to do this in ASP.Net?

C#
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();
}
}
} 
 
Share this answer
 
Comments
Uday P.Singh 19-Sep-11 6:19am    
my 5!
C#
string strFilePath = "./downloads/filename.txt";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFilePath);
                Response.WriteFile(strFilePath);
                Response.End();


This link will help you

http://dotnetslackers.com/community/blogs/haissam/archive/2007/04/03/Downloading-Files-C_2300_.aspx[^]
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900