【发布时间】:2010-02-15 23:10:39
【问题描述】:
我需要在处理之前以编程方式下载一个大文件。最好的方法是什么?由于文件很大,我想特定的时间等待,以便我可以强制退出。
我知道 WebClient.DownloadFile()。但是似乎没有办法指定等待多长时间才能强制退出。
try
{
WebClient client = new WebClient();
Uri uri = new Uri(inputFileUrl);
client.DownloadFile(uri, outputFile);
}
catch (Exception ex)
{
throw;
}
另一种方法是使用命令行实用程序 (wget) 下载文件并使用 ProcessStartInfo 触发命令并使用 Process' WaitForExit(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;
}
有没有更好的方法?请帮忙。谢谢。
【问题讨论】:
-
我试过第一个,效果很好。
标签: c# webclient download large-files