FTP使用C#和.NET4从内存中使用后台工作程序和进度条上传字符串

时间:2013-12-09 20:06:56

标签: c# .net-4.0 ftp backgroundworker

我的问题类似于this onethis one,但我无法让其中任何一个在我的应用程序中运行。也许我错过了什么?

这是我想要完成的事情:

  • 通过FTP上传字符串从内存中
  • 使用后台工作人员显示和更新进度条

以下是我现在的代码:

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

该程序跳过while块,因为total_bytes始终等于messageContent.Length。我对FTP上传知之甚少,不知道缓冲的作用以及我应该做的不同。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您将total_bytes设置为等于messageContent.Length,然后检查它是否小于int total_bytes = (int)messageContent.Length; //this is the area I need the most help with while (total_bytes < messageContent.Length) 。如果将它们设置为相等,那怎么可能更少?

{{1}}