C# - 使用UploadFileAsync进行FTP上传,并在控制台上使用进度

时间:2016-05-12 16:34:03

标签: c# ftp webclient

我是C#的新手,我想在控制台上显示进度进行FTP上传。我的代码如下所示,来自MSDN示例的一些帮助。

using System;
using System.Net;
using System.IO;
using System.Threading.Tasks;

namespace FTPUpload
{
    class FTPClient
    {
        public void Upload()
        {
            string localFile = @"D:\Applications\python-3.3.0.msi";
            string destPath = "ftp://127.0.0.1/python-3.3.0.msi";

            if (File.Exists(localFile))
            {
                Console.WriteLine(localFile + " exists!");
            }
            else
            {
                Console.WriteLine(localFile + " doesn't exists!");
            }

            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential("Anonymous", "Anonymous");
                client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
                client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadCompleted);

                client.UploadFileAsync(new Uri(destPath), localFile);

                Console.WriteLine("Upload started");
            }
        }

        public void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
        {
            Console.WriteLine(e.TotalBytesToSend);
        }

        public void UploadCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            Console.WriteLine(e.Result);
        }

        public static void Main(string[] args)
        {
            FTPClient ftpClient = new FTPClient();
            ftpClient.Upload();

        }
    }
}

我认为我没有正确编写它并且我试图在Google中搜索找不到任何关于此的示例。

请指出我正确的方向。

我已经看到了这一点但却无法明白这一点 File is not uploaded to FTP server on some machines when using WebClient.UploadFileAsync

谢谢!

0 个答案:

没有答案