c# 4.0 - 一旦大小小于缓冲区长度 c#,下载就不起作用
本文关键字:下载 不起作用 缓冲区 小小 小于 | 更新日期: 2023-09-27 17:51:03
今天,在执行下载大尺寸文件的逻辑时,我遇到了一个错误。为了下载我的逻辑,将文件分成 10KB 块,然后集成它并正在下载。虽然下载发生的事情就像每次将总大小减少 10KB ,但是一旦剩余长度小于 10KB,我的下载就会中断。请找到我的以下代码,如果我的逻辑需要任何更改,请告诉我。
protected void btnDownload_Click(object sender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
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 = "C:''Users''GZT00000000000001020''Desktop''123.zip";
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
Page.Response.ContentType = "application/octet-stream";
Page.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Page.Response.IsClientConnected)
{
if( (dataToRead < 10000) && (dataToRead!=-1))
{
length = (int)dataToRead;
buffer = new Byte[length];
dataToRead = -1;
}
else
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
}
// Write the data to the current output stream.
Page.Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Page.Response.Flush();
if (dataToRead > 10000)
{
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else if(dataToRead!=-1)
{
length =(int)dataToRead ;
buffer = new Byte[length];
}
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Page.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Page.Response.Close();
}
});
}
您不会在dataToRead
<10000 的分支中调用iStream.Read