65.9K
CodeProject 正在变化。 阅读更多。
Home

C# Web 文件下载与 BITSadmin

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1投票)

2013 年 1 月 28 日

CPOL
viewsIcon

17347

当 WebClient、HttpRequest 以及其他方法都失败时,BITSadmin 解决了你的下载难题

引言

我正在开发一个需要从网站下载文件的应用程序。过去,我使用过 WebClient(在大多数情况下都很优秀)、HttpWebRequest(笨拙)甚至 Forms WebBrowser(非常混乱)来完成这项任务。然而,对于这个特定的应用程序,由于可怕的“服务器协议违规”错误,所有这些方法都失败了。啊!!!经过一番搜索,我发现了一个合适的控制台可执行文件,所以我编写了一个简单的函数在我的应用程序中使用它。成功了!

使用代码 

简要描述如何使用本文或代码。包括
类名、方法和属性,以及任何技巧或提示。

代码块应设置为样式 "Formatted"
这样的内容。

string local = @”C:\Users\metastruct\Desktop\my_image.jpg”;

string remote = @”http://www.test.com/some_image.jpg”;

download(remote, local);

如此易于使用!

代码

private void download(string remote_file_url, string local_file)
{
    try
    {
        /* Create the Process */
        System.Diagnostics.Process bitsadmin_process = new System.Diagnostics.Process();
        /* Assign the BITSadmin Executable and Arguements to the Process */
        bitsadmin_process.StartInfo = new System.Diagnostics.ProcessStartInfo(“bitsadmin”, “/transfer mydownloadjob  /download /priority normal “ + remote_file_url + ” “ + local_file);
        /* Start the Process */
        bitsadmin_process.Start();
        /* Wait While the File Downloads */
        bitsadmin_process.WaitForExit();
        /* Dispose the Process */
        bitsadmin_process = null;
    }
    catch { }

    return;
} 

一个如此简单的解决方案来解决一个令人恼火的问题。注意:下载到共享驱动器给我带来了问题,所以我下载到本地,然后使用 File.Copy() 进行传输。下一步将是改进进程的错误处理/重定向,但目前这可行。更多信息请访问 http://meta-struct.com/

© . All rights reserved.