如何以编程方式下载C#中的大文件

hIp*_*pPy 8 c# webclient download large-files

我需要以编程方式下载大文件,然后再进行处理.最好的方法是什么?由于文件很大,我想要特定的时间等待,以便我可以强行退出.

我知道WebClient.DownloadFile().但似乎没有办法确定等待一段时间以便强行退出.

try
{
    WebClient client = new WebClient();
    Uri uri = new Uri(inputFileUrl);
    client.DownloadFile(uri, outputFile);
}
catch (Exception ex)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用命令行实用程序(wget)下载文件并使用ProcessStartInfo触发命令并使用Process'WellForExit(int ms)强制退出.

ProcessStartInfo startInfo = new ProcessStartInfo();
//set startInfo object

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        //wait for time specified
        exeProcess.WaitForExit(1000 * 60 * 60);//wait till 1m

        //check if process has exited
        if (!exeProcess.HasExited)
        {
            //kill process and throw ex
            exeProcess.Kill();
            throw new ApplicationException("Downloading timed out");
        }
    }
}
catch (Exception ex)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?请帮忙.谢谢.

Rem*_*anu 19

使用WebRequest并获取响应流.然后从响应Stream读取字节块,并将每个块写入目标文件.这样,如果下载时间过长,您可以控制何时停止,因为您可以在块之间进行控制,并且可以根据时钟确定下载是否超时:       

        DateTime startTime = DateTime.UtcNow;
        WebRequest request = WebRequest.Create("http://www.example.com/largefile");
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            using (Stream fileStream = File.OpenWrite(@"c:\temp\largefile")) { 
                byte[] buffer = new byte[4096];
                int bytesRead = responseStream.Read(buffer, 0, 4096);
                while (bytesRead > 0) {       
                    fileStream.Write(buffer, 0, bytesRead);
                    DateTime nowTime = DateTime.UtcNow;
                    if ((nowTime - startTime).TotalMinutes > 5) {
                        throw new ApplicationException(
                            "Download timed out");
                    }
                    bytesRead = responseStream.Read(buffer, 0, 4096);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)


BFr*_*ree 7

如何DownloadFileAsync在WebClient类中使用.走这条路的很酷的事情是你可以通过调用取消操作,CancelAsync如果它需要太长时间.基本上,调用此方法,如果超过指定的时间,请调用Cancel.