Upload progress in WCF

Uploading a file in WCF is done via a stream that is send to the service in a message. The service then reads the stream to the end and writes everything to disk or memory or whatever. Now I want to report the progress of this file upload to my user. Here is how it’s done: create your own stream implementation and report progress from the Read method. Origional idea is here

// report progress of the stream read with event ProgressChanged
public class StreamWithProgress : System.IO.Stream
{
   private readonly System.IO.FileStream file;
   private readonly long length;
   private long bytesRead;

   public event EventHandler<decimal> ProgressChanged;

   public StreamWithProgress(System.IO.FileStream file)
   {
      this.file = file;
      length = file.Length;
      bytesRead = 0;
      if (ProgressChanged != null) ProgressChanged(this, 0));
   }

   public override int Read(byte[] buffer, int offset, int count)
   {
       int result = file.Read(buffer, offset, count);
       bytesRead += result;
       // report percentage read
       if (ProgressChanged != null) ProgressChanged(this, 100*bytesRead/length));
       //System.Threading.Thread.Sleep(10); // for simulating slow connection
       return result;
    }

   // other stuff you want, like overrides that throw NotImplementedException
}
// usage snippet
using (var stream = System.IO.File.OpenRead(fileName))
{
   using (var progressStream = new StreamWithProgress(stream))
   {
      progressStream.ProgressChanged += new EventHandler<decimal>(UploadProgressChanged);
      var msg = new MessageWithStream(progressStream);
      using (var proxy = CreateAndOpenProxy(Server, Username, Password))
      {
         proxy.UploadFile(msg);
      }
   }
}

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.