windows form c#ftp uploader

时间:2017-03-29 13:19:43

标签: c# ftp

我在使用c#将文件上传到ftp服务器时遇到问题。

窗口窗体打开但是当我点击上传按钮时没有任何反应。 我为ftp日志记录信息和要上载的文件创建了一个结构。 我认为它是问题所在的do_work函数,但我似乎无法找到它。

struct FtpSetting
{
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FileName { get; set; }
    public string Fullname { get; set; }
}

FtpSetting inputParameter;


private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string filename = ((FtpSetting)e.Argument).FileName;
    string fullname = ((FtpSetting)e.Argument).Fullname;
    string username = ((FtpSetting)e.Argument).Username;
    string password = ((FtpSetting)e.Argument).Password;
    string server = ((FtpSetting)e.Argument).Server;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}",server,filename)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(fullname);
    byte[] buffer = new byte[1024];
    double total = (double)fs.Length ;
    int byteRead = 0;
    double read = 0;
    do
    {
        if (!backgroundWorker.CancellationPending)
        {
            byteRead = fs.Read(buffer, 0, 1024);
            ftpStream.Write(buffer, 0, byteRead);
            read += (double)byteRead;
            double pourcentage = read / total * 100;
            backgroundWorker.ReportProgress((int)pourcentage);
        }

    } while (byteRead != 0);
    fs.Close();
    ftpStream.Close();

}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

class Test
    {
        public Test()
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
        }
    }