从 FTP 服务器上下载并保存文件

本例演示如何运用 C# 中的 FtpWebRequest 等对象从 FTP 服务器上获取文件,并结合 Stream 对象中的方法来保存下载的文件:

using System;
using System.IO;
using System.Net;

namespace ConsoleApp
{
    class Program
    {
        static void Main()
        {
            FtpWebRequest reqFtp = null;
            FtpWebResponse responseFtp = null;
            Stream stream = null;

            //ftp服务器信息
            string ftpFilePath = "ftp://200.16.220.100/test.xls";
            string ftpAccount = "sa";
            string ftpPassword = "psd123";
            string localFilePath = @"d:	est.xls";

            try
            {
                //初始化FtpWebRequest对象
                reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(ftpFilePath));
                reqFtp.Timeout = 5 * 60 * 1000;
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFtp.UseBinary = true;
                reqFtp.UsePassive = true;
                reqFtp.EnableSsl = false;
                reqFtp.Credentials = new NetworkCredential(ftpAccount, ftpPassword);
                responseFtp = (FtpWebResponse)reqFtp.GetResponse();
                stream = responseFtp.GetResponseStream();

                //保存文件到本地磁盘
                SaveFile(localFilePath, stream);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
        }

        /// <summary>
        /// 把文件流中的数据写入到文件中
        /// </summary>
        /// <param name="fileFullPath">文件的绝对路径</param>
        /// <param name="inputStream">文件流</param>
        public static void SaveFile(string fileFullPath, Stream inputStream)
        {
            using (FileStream fileStream = new FileStream(fileFullPath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (BufferedStream buffStream = new BufferedStream(inputStream))
                {
                    int buffSize = 1024;
                    byte[] buff = new byte[buffSize];

                    //将字节从当前缓冲流读取到数组
                    int readCount = 0;
                    readCount = buffStream.Read(buff, 0, buffSize);

                    while (readCount > 0)
                    {
                        //将字节块写入文件流
                        fileStream.Write(buff, 0, readCount);
                        //由于读到流的最后一段时,流会自动关闭
                        //这里需要判断流是否可读,
                        //若不可读,说明读完了最后一段,可以结束
                        if (buffStream.CanRead)
                        {
                            readCount = buffStream.Read(buff, 0, buffSize);
                        }
                        else
                        {
                            readCount = 0;
                            break;
                        }
                    }
                }

                //清除此流的缓冲区,使得所有缓冲的数据都写入到文件中
                fileStream.Flush();
                //关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
                fileStream.Close();
            }
        }
    }
}

下面的方法用于判断文件目录是否存在,如果不存在就新建目录:

private static Boolean FtpMakeDir(string ftpServerIP, string ftpUserID, string ftpPassword, string localFile)
{
    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + localFile));
    req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    req.Method = WebRequestMethods.Ftp.MakeDirectory;            
    try
    {
        FtpWebResponse response = (FtpWebResponse)req.GetResponse();                                
        response.Close();
    }
    catch (Exception ex)
    {
        req.Abort();
        return false;
    }
    finally
    {
        req.Abort();
    }
    return true;
}

参考资源:

https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx

http://bbs.csdn.net/topics/390627456

原文地址:https://www.cnblogs.com/hellowzl/p/6768341.html