My question is similar to this one and this one, but I couldn't get either of them to work in my application. Perhaps I'm missing something?
Here is what I want to accomplish:
- Upload a string from memory via FTP
- Show and update a progress bar with a background worker
And here is the code I have now:
private void bkgd_Submit_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
string host = @"ftp://ftp.somesite.net/submissions/";
string user = "username";
string pass = "password";
string[] lines = { "First line", "Second line", "Third line" };
string ftpFile = host + "filename.txt";
//the string that needs to get uploaded
string message = "Hello this is the first order.";
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpFile);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.KeepAlive = false;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.UseBinary = true;
byte[] messageContent = Encoding.ASCII.GetBytes(message);
ftpRequest.ContentLength = messageContent.Length;
int buffLength = 2048;
Stream ftpStream = ftpRequest.GetRequestStream();
int total_bytes = (int)messageContent.Length;
//this is the area I need the most help with
while (total_bytes < messageContent.Length)
{
ftpStream.Write(messageContent, total_bytes, buffLength);
total_bytes += buffLength;
var progress = total_bytes * 100.0 / messageContent.Length;
bkgd_Submit.ReportProgress((int)progress);
}
ftpStream.Close();
}
The program skips over the while
block, because total_bytes
is always equal to messageContent.Length
. I don't know enough about FTP uploading to know what the buffering does and what I should be doing differently.
Thanks so much for your help!