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);
}
}
}