采用下面的函数向客户端输出下载文件,存在一个问题:在第一次下载中途时如果客户端终止,那么再次下载时就会出现死循环,似乎用Response.IsClientConnected并不能判断客户端是否仍然在下载,请高手给予指点:

public void WriteFile(HttpContext context,string FilePath)
{
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 name.
string  filename  = System.IO.Path.GetFileName(FilePath); context.Response.Clear(); 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; context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (context.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream.
context.Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output.
context.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.
context.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
context.Response.Clear();
context.Response.End();
}}

解决方案 »

  1.   

    下面这句有问题,
    length = iStream.Read(buffer, 0, 10000);返回值:或者如果已到达流的末尾,则为零,应该判断一下,如果 length <= 0,就要 break 循环了。!
      

  2.   

    谢谢楼上,但是如果length<=0,那么DataToRead的值也等于0了,自己会退出循环的。而且循环的条件是datatoread而不是length!
      

  3.   

    还有个问题,你们有没发现:
    你有没发现,使用下面这条语句,
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
    当 filename 为中文名时,它产生的下载对话框中的文件名确是乱码. 真是怪事!