wasnt nate

Using BITS Protocol from C#

For a recent project; I needed to download huge files across the network. To perform this I enabled BITS extension for IIS and then used the System.Net.BITS library written by RogerB.

First the BITS manager needs to be initialized; this will create the managed wrapper to the out of proc COM server which.

BitsManager = new Manager();
BitsManager.OnModfication += 
  new EventHandler<JobModificationEventArgs>
       (BitsManager_OnModfication);

Downloading the file was fairly straight foward

void StartDownloading(string remoteUri, string localUri)
{
  var job = new Job(cacheRecord.RemoteUri);
  job.Tag = cacheRecord;

  job.Files.Add(remoteUri, localUri);
  BitsManager.Jobs.Add(job);
  job.Resume();
}
// StartDownload("http://webserver/file.vhd",@"c:\cache\file.vhd");

The only part left is to report progress and wait until it finishes. While downloading the file will be held in the destination folder with a random filename marked with the hidden file attribute. This file will not be visible or renamed to the expected value until job.Complete() is called.

void BitsManager_OnModfication
       (object sender, JobModificationEventArgs e)
{
  var cacheRecord = e.Job.Tag as VhdCacheRecord;
  var progress = e.Job.Progress;

  var percentComplete = (int) 100 * 
     (((float)progress.BytesTransferred/(float)progress.BytesTotal);

  DoSomethingWithProgress(percentComplete);     
  if (percentComplete == 100)
  {
    e.Job.Complete();
  }
}

If you need more help in debugging this library or other BITS communication; take a look at BITSAdmin, provided as a free tool and is part of Windows.

When running BITSAdmin on Windows 7 and higher there is warning “BITSAdmin is deprecated and is not guaranteed to be available in future version  of Windows. Administrative tools for the BITS service are now provided by BITS PowerShell commandlets.”

To be one of the cool kids that uses the new technology run the following commands from the PowerShell command prompt.

PS C:\> Import-Module BitsTransfer
PS C:\> man BitsTransfer

Leave a Reply