科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道C#实现大文件分块发送到客户端

C#实现大文件分块发送到客户端

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000];

作者:中国IT实验室 来源:中国IT实验室 2007年9月7日

关键字: 客户端 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();
  }
 }

查看本文来源

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章