FTP上传/下载文件栗子

今天闲暇时,做了个FTP上传下载文件Demo。栗子很简单,就是自己封装的一个FTPHelper类型。直接贴出代码

   public class FtpHelper
    {
        private static FtpHelper _instance;
        private static object locker = new object();
        private FtpHelper() { }

        private  string path = @"ftp://" + ConfigurationManager.AppSettings["FtpServerIP"].ToString() + "/";  //目标路径
        private  string ftpip = ConfigurationManager.AppSettings["FtpServerIP"].ToString();  //ftp IP地址
        private  string username = ConfigurationManager.AppSettings["FtpUserName"].ToString();  //ftp用户名
        private  string password = ConfigurationManager.AppSettings["FtpPassWord"].ToString();  //ftp密码
        public static FtpHelper Instance{
            get {
                if (_instance == null)
                {
                    lock (locker)
                    {
                        if (_instance == null)
                            _instance = new FtpHelper();
                    }
                }
                return _instance;
            }
        }

        #region 上传
        public  bool UploadFile(string filepath) {
            bool result = true;
            try
            {
               
                //创建FTP对象
                var request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)+Path.GetFileName(filepath));
                //设置请求参数
                request.Credentials = new NetworkCredential(username, password);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.UseBinary = true;
                request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
                request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
                //将文件内容读入请求对象中
                using (FileStream fs = new FileStream(filepath, FileMode.Open))
                {
                    using (var requstStream = request.GetRequestStream())
                    {
                        int readSize = 2048;
                        byte[] temp = new byte[2048];
                        bool isNext = fs.Read(temp, 0, readSize) > 0;
                        while (isNext)
                        {
                             requstStream.Write(temp, 0, readSize);
                             var s = fs.Position;
                             isNext = fs.Read(temp, 0, readSize)> 0;
                             s = fs.Position;
                        }
                    }

                }
            }
            catch (Exception ex)
            {

                result =  false;
            }
           
            //返回操作结果
            return result;
        }
        #endregion

        #region 下载
        public  bool DownLoadFile(string filename,string saveDir)
        {
            bool result = true;
            try
            {
                var request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path) + filename);
                //设置请求参数
                request.Credentials = new NetworkCredential(username, password);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.UseBinary = true;
                request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
                request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。 
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream fs = new FileStream(saveDir + filename, FileMode.CreateNew);
                int readSize = 2048;
                byte[] temp = new byte[2048];
                bool isNext = responseStream.Read(temp, 0, readSize) > 0;
                while (isNext)
                {
                    fs.Write(temp, 0, readSize);
                    isNext = responseStream.Read(temp, 0, readSize) > 0;
                }
                responseStream.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region 获取文件
        //获取ftp上面的文件和文件夹
        public  string[] GetFiles(string dir)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir));
                request.UseBinary = true;
                request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary = true;
                request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
                request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }

                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
           
                downloadFiles = null;
                return downloadFiles;
            }
        }
        #endregion


    }
View Code

测试代码:

            #region FTP上传/下载文件测试
            //获取文件列表
            foreach (var item in FtpHelper.Instance.GetFiles(null))
            {
                Console.WriteLine(item);
            }

            //批量上传文件
            Thread thread = new Thread(() =>
            {
                var files = Directory.GetFiles(@"D:\健身视频");
                foreach (var file in files)
                {
                    bool? res = default(bool?);
                    string filename = Path.GetFileName(file);
                    Console.WriteLine("正在上传:" + filename);
                    res = FtpHelper.Instance.UploadFile(file);
                }
                Console.WriteLine("上传完毕!");
            });
            thread.IsBackground = true;
            thread.Start();
            thread.Join();

            //下载文件
            string saveDir = @"E:\项目\PatternStu\PatternStu\Content\DownLoad\";
            string fileName = "IMG_20160303_174423.jpg";
            Console.WriteLine("正在下载:" + fileName);
            FtpHelper.Instance.DownLoadFile(fileName, saveDir);
            Console.WriteLine("下载完成!");
            #endregion

            Console.ReadKey();
View Code

 

posted on 2018-09-05 16:01  潇潇@暮雨  阅读(198)  评论(0编辑  收藏  举报

导航