FileInfo DownloadFile = new FileInfo(path);
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8).Replace("+", "%20"));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            Response.End();将文件下载,我现在想捕捉到他何时完成,请高手指点。

解决方案 »

  1.   

    webform似乎没有这个事件
    你说的是winform的进度条吧
      

  2.   

    可以采用分批读取数据的方法,这样就可以判断下载是否完成,参考下面的代码:
    try {
                    // Open the file.
                    iStream = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                    // Total bytes to read:
                    dataToRead = iStream.Length;                Response.ContentType = "Application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + name + "." + ext);
                    Response.AddHeader("Content-Length", dataToRead.ToString());                while (dataToRead > 0) {
                        // Verify that the client is connected.
                        if (Response.IsClientConnected) {
                            // Read the data in buffer.
                            length = iStream.Read(buffer, 0, FILE_BUFFER);                        // 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[FILE_BUFFER];
                            dataToRead = dataToRead - length;
                        } else {
                            //prevent infinite loop if user disconnects
                            dataToRead = -1;
                        }
                        // Download finished
                    }
                } catch (Exception ex) {
                    Utility.LogUtility.WriteToLog(ex, this.GetType(), "下载文件错误");
                    throw ex;
                } finally {
                    if (iStream != null) {
                        iStream.Close();
                    }
                }
      

  3.   

    除非文件特别小,比如1KB或以下,否则永远不要使用WriteFile去下载文件。