使用Webclient.UploadFileAsync

时间:2015-09-27 18:59:05

标签: c#

我正在向我的包装器发送多个文件,将文件发送到ftp。我必须得到上传的进度,所以我必须使用asycn方法进行上传。问题是,如何通过一个方法调用上传器一,还能得到进度报告吗?

2 个答案:

答案 0 :(得分:3)

如果你想等待每个文件,这是一个解决方案:

class FileUploader
{
    private readonly Uri _destination;

    public FileUploader(Uri destination)
    {
        _destination = destination;
    }

    public void UploadFiles(IEnumerable<string> fileNames)
    {
        foreach (var fileName in fileNames)
        {
            UploadFile(fileName);
        }
    }

    private void UploadFile(string fileName)
    {
        var tcs = new TaskCompletionSource<bool>();
        using (var client = new WebClient())
        {
            client.UploadProgressChanged += UploadProgressChangedHandler;
            client.UploadFileCompleted += (sender, args) => UploadCompletedHandler(fileName, tcs, args);
            client.UploadFileAsync(_destination, fileName);
            tcs.Task.Wait();
        }
    }

    private void UploadCompletedHandler(string fileName, TaskCompletionSource<bool> tcs, UploadFileCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            tcs.TrySetCanceled();
        }
        else if (e.Error != null)
        {
            tcs.TrySetException(e.Error);
        }
        else
        {
            tcs.TrySetResult(true);
        }
    }

    private void UploadProgressChangedHandler(object sender, UploadProgressChangedEventArgs e)
    {
        // Handle progress, e.g.
        System.Diagnostics.Debug.WriteLine(e.ProgressPercentage);
    }
}

答案 1 :(得分:2)

您必须订阅UploadProgressChanged事件:

var client = new WebClient();
client.UploadProgressChanged += (s, e) => System.Diagnostics.Debug.WriteLine(e.ProgressPercentage);
client.UploadFileAsync(new Uri("ftp://server/directory"), @"C:\temp\file.txt");
client.UploadFileCompleted += (s, e) => Task.Factory.StartNew(client.Dispose);