简体   繁体   中英

FTP Upload string from memory with background worker and progress bar using C# and .NET4

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!

You're setting total_bytes to be equal to messageContent.Length , then checking to see if it's less that that. How can it be less when you just set them to be equal ?

int total_bytes = (int)messageContent.Length;

//this is the area I need the most help with
while (total_bytes < messageContent.Length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM