现在的位置: 首页 >> 程序开发 >> C#.NET >> C#实现大文件分块发送到客户端
添加时间:2005-10-30 来源:网教中国 作者:
C#实现大文件分块发送到客户端

System.IO.Stream iStream = null;

 // Buffer to read 10K bytes in chunk:
 byte[] buffer = new Byte[10000];

 // Length of the file:
 int length;

 // Total bytes to read:
 long dataToRead;

 // Identify the file to download including its path.
 string filepath  = "DownloadFileName";

 // Identify the file name.
 string  filename  = System.IO.Path.GetFileName(filepath);

 try
 {
  // Open the file.
  iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
     System.IO.FileAccess.Read,System.IO.FileShare.Read);


  // Total bytes to read:
  dataToRead = iStream.Length;

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

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

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

    // Flush the data to the HTML output.
    Response.Flush();

    buffer= new Byte[10000];
    dataToRead = dataToRead - length;
   }
   else
   {
    //prevent infinite loop if user disconnects
    dataToRead = -1;
   }
  }
 }
 catch (Exception ex)
 {
  // Trap the error, if any.
  Response.Write("Error : " + ex.Message);
 }
 finally
 {
  if (iStream != null)
  {
   //Close the file.
   iStream.Close();
  }
 }

 


上一篇:使用C#编写一个计时器 下一篇:C#实现SMTP服务器,使用TCP命令实现,功能比较完善
大部分文章摘自网上,如有侵犯您的权益请与我们联系,我们会第一时间进行处理,谢谢! [ 打印文章 ] [ 关闭窗口 ]
推荐文章
·Snake.Net中的ORM(三)
·Visual C#托管Socket的实现方法(
·对.NET Framework "事件"机制理
·C#锐利体验(3.2)
·在C#中使用COM+实现事务控制
·.NET Remoting编程简介
·全面剖析VB.NET(3)
·微软的远程处理框架.NET Remotin
·C#重点知识详解(一)
·冰雹欲来风满楼--.NET计划初露锋
相关文章
 
最新文章
·数据结构与算法(C#实现)系列---(
·数据结构与算法(C#实现)系列---(
·数据结构与算法(C#实现)系列---(
·ASP.net 验证码(C#)
·Snake.Net中的ORM(三)
·Snake.Net中的ORM(二)
·Snake.Net中的ORM(-)
·用C#生成随机中文汉字验证码的基
·Autodesk官方最新的.NET教程(五
·Autodesk官方最新的.NET教程(四
Google