C# Web File Download with BITSadmin

I was making an app that required downloading files from a website.  In the past, I’ve used WebClient (excellent for most scenarios), HttpWebRequest (clunky), and even the Forms WebBrowser (very messy) to accomplish the deed.  For this particular app however, all of these methods failed due to the dreaded “server protocol violation” error.  Argh!!!  With some digging, I found a console executable that was right for the job, so I made a simple method to use it in my app.  Success!

//
//

Using the method

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

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

download(remote, local);

That easy to use!  Below is the code snippet:

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;

}

Such a simple solution to such an annoying problem.  Next step would be some improved error handling/redirection from the Process, but this works for now.

Advertisements
Tagged with: , , , , , ,
Posted in Uncategorized
4 comments on “C# Web File Download with BITSadmin
  1. hello,
    I’m trying to do file sharing between two PCs by implementing the FTP using C#. This code is for receiver I think. how can I do this for transmitter?
    .

  2. ron says:

    Hi, is there a way that I can remember the credentials for the FTP Client?, other than hard coding the username, password and host in the codes. It means that when I close my client and reopened it, it still have the credentials, I need this since I will register the app in the scheduled task. Thanks.

    • metastruct says:

      I would imagine connecting to a database with login info would work or you could just simply put it in a text file and have the app read the file any time it connects to grab the latest password.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: