编码在C#中下载 [英] Coading to download in C#
本文介绍了编码在C#中下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我们单击下载按钮时,如何在C#点网中下载文件和照片?
How to download file and photo in C# Dot Net when we click on download button ?
推荐答案
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();
}
}
}
string strFilePath = "./downloads/filename.txt";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFilePath);
Response.WriteFile(strFilePath);
Response.End();
此链接将为您提供帮助
http://dotnetslackers.com/community/blogs/haissam/存档/2007/04/03/Downloading-Files-C_2300_.aspx [
This link will help you
http://dotnetslackers.com/community/blogs/haissam/archive/2007/04/03/Downloading-Files-C_2300_.aspx[^]
请参阅此
http://codes.codedigest.com/CodeDigest/39 -File-Download-in-ASP-Net-with-C-.aspx [
refer this
http://codes.codedigest.com/CodeDigest/39-File-Download-in-ASP-Net-with-C-.aspx[^]
这篇关于编码在C#中下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文