I am trying to upload a file via FTP, and want to report progress to the user. I was following this suggestion, but couldn't make it work.
If I call the code synchronously, it works fine...
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpserver.com/test.zip");
request.Credentials = new NetworkCredential("uid", "pwd");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (FileStream inputStream = File.OpenRead(@"D:\test.zip")) {
using (Stream outputStream = request.GetRequestStream()) {
byte[] buffer = new byte[64 * 64];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0) {
outputStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
int progress = (int)(totalReadBytesCount * 100.0 / inputStream.Length);
Debug.WriteLine(" " + progress + "%");
}
}
}
...but if I try and wrap the code in a BackgroundWorker, it fails silently. I have tried adding a try/catch block around it, but I don't get an exception.
Here is the BGW version of the code...
BackgroundWorker bg = new BackgroundWorker {
WorkerReportsProgress = true
};
bg.DoWork += (s, e) => {
try {
Debug.WriteLine("DoWork");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpserver.com/test.zip");
Debug.WriteLine("DoWork - Setting up creds");
request.Credentials = new NetworkCredential("uid", "pwd");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (FileStream inputStream = File.OpenRead(@"D:\test.zip")) {
using (Stream outputStream = request.GetRequestStream()) {
byte[] buffer = new byte[64 * 64];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0) {
Debug.WriteLine(" DoWork - Inside");
outputStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
double progress = totalReadBytesCount * 100.0 / inputStream.Length;
Debug.WriteLine(" " + progress + "%");
bg.ReportProgress((int)progress);
}
}
}
}
catch (Exception ex) {
Debug.WriteLine("Exception: " + ex.Message);
}
};
bg.ProgressChanged += (s, e) => {
Debug.WriteLine(e.ProgressPercentage + "%");
};
bg.RunWorkerCompleted += (s, e) => {
Debug.WriteLine("Done");
};
bg.RunWorkerAsync();
}
I get the "DoWork" line written to the Output window, but then nothing else. If I put a breakpoint on the line that sets up the FtpWebRequest, execution immediately ends after that line, but I don't get an exception.
Anyone any ideas? Could be I'm doing this wrong. I want to upload async, and have a progress indicator. Is this even the best way to do it?