c#中的异步下载文件

时间:2016-04-19 09:59:54

标签: c#

我需要帮助来改进此代码,但我不明白我在哪里犯了错误。文件已下载但格式已损坏。我也在使用cookie,这是此方法的必要部分。

/*Downlod task */
public static async Task<int> CreateDownloadTask(string urlToDownload,string sDestinationPath, string cookiedstr)
{
    int BufferSize = 4096;
    int receivedBytes = 0;
    int totalBytes = 0;
    WebClient client = new WebClient();
    client.Headers.Add(HttpRequestHeader.Cookie, cookiedstr);

    using (var stream = await client.OpenReadTaskAsync(urlToDownload))
    {
        using (MemoryStream ms = new MemoryStream())
        {
            int read = 0;
            totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);
            var buffer = new byte[BufferSize];
            while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
                FileStream file = new FileStream(sDestinationPath, FileMode.Append, FileAccess.Write);
                ms.Position = 0;
                ms.WriteTo(file);
                file.Flush();
                file.Close();
                buffer = new byte[BufferSize];
                receivedBytes += read;
                Console.WriteLine(receivedBytes + " " + totalBytes);
                // DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
            }
            ms.Close();
        }
        return receivedBytes;
    }
}

0 个答案:

没有答案