ASP.Net Web表单:带上进程的FTP上载

时间:2014-10-28 16:10:25

标签: c# asp.net webforms ftp ftpwebrequest

我也在ASP.Net论坛上发布了这个问题:http://forums.asp.net/t/2014412.aspx?FTP+Upload+with+Progress

我的情况是我需要通过FTP(带凭据)将上传保存到另一台服务器(即不是网络服务器)。我已经能够做到这一点,但我无法理解如何向GUI展示进展。

我被建议使用后台工作者,但这并没有更新GUI。这是我的尝试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    BackgroundWorker backgroundWorker1 = new BackgroundWorker();


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        var fileName = @"c:\myfile.zip";
        var ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://servername/myfile.zip"));
        ftpWebRequest.Credentials = new NetworkCredential("myusername", "mypassword");
        ftpWebRequest.KeepAlive = false;
        ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
        ftpWebRequest.UseBinary = true;
        FileInfo fileInf = new FileInfo(fileName);

        //Notify the server about the size of the uploaded file
        ftpWebRequest.ContentLength = fileInf.Length;


        ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
        using (var inputStream = File.OpenRead(fileName))
        using (var outputStream = ftpWebRequest.GetRequestStream())
        {
            var buffer = new byte[1024 * 1024];
            int totalReadBytesCount = 0;
            int readBytesCount;
            while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, readBytesCount);
                totalReadBytesCount += readBytesCount;
                var progress = totalReadBytesCount * 100.0 / inputStream.Length;
                backgroundWorker1.ReportProgress((int)progress, totalReadBytesCount);
            }
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {       
            progressBar.Value = e.ProgressPercentage;
            percentTB.Text = e.ProgressPercentage + "%";       
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.RunWorkerAsync();
    }

    private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // log when the worker is completed.
    }
}

感谢任何建议。

0 个答案:

没有答案