下载有时不完整,没有任何错误或异常

本文关键字:任何 错误 异常 下载 | 更新日期: 2023-09-27 18:17:09

        // It will store the current number of bytes we retrieved from the server
        int bytesSize = 0;
        // A buffer for storing and writing the data retrieved from the server
        byte[] downBuffer = new byte[10240];
        bool exceptionOccured = false;
        HttpWebRequest webRequest = null;
        try
        {

// Create a request to the file we are downloading
webRequest = (HttpWebRequest)WebRequest.Create(urlAndChecksum.FILEURL);
webRequest.Timeout = 120000;
webRequest.ReadWriteTimeout = 300000;
webRequest.ConnectionGroupName = mediaName;
// Set default authentication for retrieving the file
//webRequest.Credentials = new NetworkCredential(GlobalVariables.username, GlobalVariables.password);
webRequest.UseDefaultCredentials = true;
// Retrieve the response from the server
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
    // Open the URL for download 
    strResponse = webResponse.GetResponseStream();
    // Create a new file stream where we will be saving the data (local drive)
    strLocal = File.Create(destFilePath);
    // Loop through the buffer until the buffer is empty
    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
    {
        if (isPaused)
        {
            Logger.WriteToLog(mediaName);
            waitRun_m.WaitOne();
        }
        if (isCanceled)
        {
            Logger.WriteToLog("Before Cancel :: Concurrent connections = " + webRequest.ServicePoint.CurrentConnections);
            webResponse.Close();
            //webRequest.Abort();
            webRequest.ServicePoint.CloseConnectionGroup(mediaName);
            Logger.WriteToLog("After Cancel :: Concurrent connections = " + webRequest.ServicePoint.CurrentConnections);
            return;
        }
        strLocal.Write(downBuffer, 0, bytesSize);
        // Invoke the method that updates the form's label and progress bar
        UpdateProgessCallback(mediaName, bytesSize);
    };
}
 catch (Exception ex)
        {
            exceptionOccured = true;
            MessageBox.Show(ex.Message, "Cadence Download Manager", MessageBoxButton.OK, MessageBoxImage.Error);
            isExceptionOccured = true;
            StopAllDownloads(Thread.CurrentThread, ex.Message, HttpStatusCode.NotFound);
        }
        finally
        {
            if (!isExceptionOccured)
            {
                if (strResponse != null)
                    strResponse.Close();
                if (strLocal != null)
                    strLocal.Close();
}
}

这是我用来从服务器下载文件的代码。有时文件没有完全下载。例如,如果我下载一个200MB的文件,它只下载50mb,并且停止,没有任何错误或异常。大多数情况下,大约80%的情况下,文件被完全下载。我的代码可能出了什么问题?

下载有时不完整,没有任何错误或异常

缺少多少字节?如果小于缓冲区大小,那么我猜你的问题是你没有正确关闭/刷新strLocal流。