// 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的文件,它下载只说50 MB并停止,不会给出任何错误或异常。大多数时间大约80%的时间,文件被完全下载。我的代码可能有什么问题?
答案 0 :(得分:-2)
缺少多少字节?如果小于缓冲区大小,那么我猜你的问题是你没有正确关闭/刷新strLocal流。