Ftp进行文件的上传和下载

一、开篇之前,先给大家推荐一款好用的FTP工具:FTP客户端—IIs7服务器管理工具
             --官网地址:http://fwqglgj.iis7.net/cp/ftp/?cmc-zc
作为FTP客户端,它支持批量管理ftp站点。定时上传和定时下载,定时备份,且操作简洁。同时iis7服务器管理工具还是vnc客户端。并且支持批量管理管理windows及linux服务器、vps。让服务器真正实现了一站式管理,真的是非常方便。

这款软件功能丰富,主要有:

   1、自动重连
   2、自动重传
   3、定时任务 (定时上传、定时下载)
   4、自定义传输模式,线程,编码
   5、删除到回收站
   6、大量文件快速加载,边加载边传输
   7、批量连接一键关闭

接下来来欣赏下界面:

 

  二、下面是.net 常用的文件上传帮助类:

 

下载:
文件操作类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
namespace FTP文件上传
{
    class FileOperate
    {
        private static FileOperate _fileOperate = null;
        private string _filePath = string.Empty;
        public string FilePath { get { return _filePath; } private set { _filePath = value; } }
        private FileInfo fileInfo = null;
        public  string[] files = null;
        public static FileOperate GetInstance()
        {
            if (_fileOperate == null)
                _fileOperate = new FileOperate();
            return _fileOperate;
        }
        public void OpenFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*|文件夹|*.File folder";
            ofd.RestoreDirectory = true;
            ofd.Multiselect = true;
            ofd.FilterIndex = 1;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                files = ofd.FileNames;
            }
        }
        public void UpLoadFile(string LocalfileName)
        {
            if (string.IsNullOrEmpty(LocalfileName))
                return;
            string url = GetUrl(ConfigManager.HostName, ConfigManager.TargetDir);
            System.Net.FtpWebRequest ftp = GetRequest(url);
            //设置FTP命令 设置所要执行的FTP命令,
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            fileInfo = new FileInfo(LocalfileName);
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            //告诉ftp文件大小
            ftp.ContentLength = fileInfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;
            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileInfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    fs.Close();
                }
            }
            ftp = null;
            //设置FTP命令
            ftp = GetRequest(url);
            ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo = fileInfo.Name;
            try
            {
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                ftp = GetRequest(url);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
                ftp.GetResponse();
                throw ex;
            }
            finally
            {
                ftp = null;
                fileInfo.Delete();
            }
            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="FtpFilePath">Ftp的文件目录</param>
        /// <param name="FtpFileName">Ftp上的文件名称</param>
        /// <param name="localFilePath">本地的文件目录</param>
        public void DownLoadFile(string FtpFilePath,string FtpFileName,string localFilePath)
        {
            if (!IsExistDir(FtpFilePath+"/"+FtpFileName))
                return;
            string url = "ftp://" + ConfigManager.HostName +  FtpFilePath+"/"+FtpFileName;
            FtpWebRequest ftp = GetRequest(url);
            ftp.Method = WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            using(FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using(Stream rsp = response.GetResponseStream())
                {
                    localFilePath = localFilePath + @"\" + FtpFileName;
                using(FileStream fs = new FileStream(localFilePath,FileMode.OpenOrCreate))
                {
                    try
                    {
                        byte[] buffer = new byte[2048];
                        int read = 0;
                        do
                        {
                            read = rsp.Read(buffer, 0, buffer.Length);
                            fs.Write(buffer, 0, read);
                        } while (!(read == 0));
                        fs.Flush();
                        fs.Close();
                    }
                    catch
                    {
                        //失败删除文件
                        fs.Close();
                        fileInfo = new FileInfo(localFilePath);
                        fileInfo.Delete();
                    }

                }
            }

            }

        }
        private static string GetUrl(string hostName, string targetDir)
        {
            string target = Guid.NewGuid().ToString();
            return "FTP://" + hostName + "/" + targetDir + "/" + target;
        }
        private static FtpWebRequest GetRequest(string url)
        {
            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(url);
            //提供身份验证信息
            result.Credentials = new System.Net.NetworkCredential(ConfigManager.UserName, ConfigManager.Password);
            //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
            result.KeepAlive = false;
            return result;
        }
        public List<string> GetDirectorysAndFiles(string requestPath)
        {
            var dict = new List<string>();
            if (!IsExistDir(requestPath))
                return dict;
            try
            {
                string url = "ftp://" + ConfigManager.HostName +  requestPath;
                FtpWebRequest ftp = GetRequest(url);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    line = line.Substring(line.LastIndexOf(' ') + 1);
                    dict.Add(line);
                    line = reader.ReadLine();
                }

                ftp = null;
                response.Close();
            }
            catch { }

            return dict;
        }
        private Boolean IsExistDir(string requestPath)
        {
            try
            {
                string url = "ftp://" + ConfigManager.HostName + "/" + requestPath;
                FtpWebRequest ftp = GetRequest(url);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var response = ftp.GetResponse();
                response.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace FTP文件上传
{
    class ConfigManager
    {
        //上传
        public static string HostName = ConfigurationManager.AppSettings["HostName"];
        public static string UserName = ConfigurationManager.AppSettings["UserName"];
        public static string Password = ConfigurationManager.AppSettings["Password"];
        public static string TargetDir = ConfigurationManager.AppSettings["TargetDir"];

        //下载
        //D:\ftp\New folder\Newfolder
        public static string SourceDir = @"/New folder/Newfolder";//一级目录前不加/
        //目标文件夹路径
        public static string LoadTargetDir = @"D:\buck";
    }
}

调用

  //  FileOperate.GetInstance().GetDirectorysAndFiles();
          //  FileOperate.GetInstance().OpenFile();
            //MessageBox.Show(FileOperate.GetInstance().FilePath);
          //  var file = FileOperate.GetInstance().files;
           // FileOperate.GetInstance().UpLoadFile("ss");
          //  FileOperate.GetInstance().GetDirectorysAndFiles("/New folder/Newfolder");
            FileOperate.GetInstance().DownLoadFile(@"/New folder/Newfolder", "11.zip", @"D:\buck");
           // MessageBox.Show();

  

posted @ 2020-04-03 16:05  谁说程序猿很猥琐  阅读(2255)  评论(1编辑  收藏  举报