How can I get file from FTP (using C#)?

后端 未结 2 563
我寻月下人不归
我寻月下人不归 2021-02-06 11:42

Now I know how to copy files from one directory to another, this is really simple.

But now I need to do the same with files from FTP server. Can you give me some exampl

2条回答
  •  春和景丽
    2021-02-06 12:38

    Easiest way

    The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile.

    It takes an URL to the source remote file and a path to the target local file. So you can use a different name for the local file, if you need that.

    WebClient client = new WebClient();
    client.Credentials = new NetworkCredential("username", "password");
    client.DownloadFile(
        "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
    

    Advanced options

    If you need greater control, that WebClient does not offer (like TLS/SSL encryption, ASCII mode, active mode, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
    {
        ftpStream.CopyTo(fileStream);
    }
    

    Progress monitoring

    If you need to monitor a download progress, you have to copy the contents by chunks yourself:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
    {
        byte[] buffer = new byte[10240];
        int read;
        while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, read);
            Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
        }
    }
    

    For GUI progress (WinForms ProgressBar), see:
    FtpWebRequest FTP download with ProgressBar


    Downloading folder

    If you want to download all files from a remote folder, see
    C# Download all files and subdirectories through FTP.

提交回复
热议问题