First of all re-write the UploadFile function as follows:-
private void UploadFile(string fileName, Stream data, Action<Exception> callback)
{
UriBuilder ub = new UriBuilder("http://localhost:3840/receiver.ashx");
ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
try
{
PushData(data, e.Result);
e.Result.Close();
data.Close(); // This blocks until the upload completes
callback(null);
}
catch (Exception er)
{
callback(er);
}
};
c.OpenWriteAsync(ub.Uri);
}
Now you can use this function like this:-
Stream data = new fi.OpenRead();
try
{
FileUpload(fi.Name, data, (err) =>
{
// Note if you want to fiddle with the UI use dispatcher Invoke here.
if (err == null)
{
// Success
}
else
{
// Fail do something with the err to disply why
}
});
}
catch
{
data.Dispose();
}