C# FTP上传、下载、删除

2022-03-23 08:51:33 浏览数 (1)

01—FTP概述

文件传输协议(File Transfer Protocol,FTP)是用于在网络上进行文件传输的一套标准协议,作为一套古老的网络工具,在工业界有着及其广泛的应用.本节主要给大家演示ftp对文件的上传、下载、以及删除。如果还没有ftp服务地址,请参考上节【使用filezilla server搭建ftp服务器】搭建下服务器。

02—效果演示

03—代码

先定义配置模型:FTPConfig

代码语言:javascript复制
 public class FTPConfig
    {
        /// <summary>
        /// 
        /// </summary>
        public FTPConfig()
        {
            IsUpload = false;
            FtpServerIP = "127.0.0.1";
            FtpRemotePath = "";
            FtpUserID = "ftpTest";
            FtpPassword = "a123456.";
        }

        /// <summary>
        /// 是否上传
        /// </summary>
        public bool IsUpload { get; set; }

        /// <summary>
        /// FTP的IP地址
        /// </summary>
        public string FtpServerIP { get; set; }

        /// <summary>
        /// 上传FTP目录
        /// </summary>
        public string FtpRemotePath { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string FtpUserID { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string FtpPassword { get; set; }
    }

FTP上传、下载、删除方法:

代码语言:javascript复制
 /// <summary>
        /// 上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(string filename)
        {
            if (ftpConfig.IsUpload)
            {
                FileInfo fileInfo = new FileInfo(filename);
                string uri = ftpURI   fileInfo.Name;
                FtpWebRequest reqFTP;

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials = new NetworkCredential(ftpConfig.FtpUserID, ftpConfig.FtpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                reqFTP.UseBinary = true;
                reqFTP.ContentLength = fileInfo.Length;

                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                using (FileStream fs = fileInfo.OpenRead())
                {
                    using (Stream strm = reqFTP.GetRequestStream())
                    {
                        try
                        {
                            contentLen = fs.Read(buff, 0, buffLength);
                            while (contentLen != 0)
                            {
                                strm.Write(buff, 0, contentLen);
                                contentLen = fs.Read(buff, 0, buffLength);
                            }
                            strm.Close();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            string errorMessage = "Upload Error --> "   ex.Message;
                            //logger.Error(errorMessage);
                            throw;
                        }
                    }
                }
            }
            else
            {
                //logger.Debug("[UploadData] uploadConfig.IsUpload is false,abort to loaddata");
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public void Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                FileStream outputStream = new FileStream(filePath   "\"   fileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI   fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpConfig.FtpUserID, ftpConfig.FtpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                string errorMessage = "Download Error --> "   ex.Message;
                //logger.Error(errorMessage);
                throw;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public void Delete(string fileName)
        {
            try
            {
                string uri = ftpURI   fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential(ftpConfig.FtpUserID, ftpConfig.FtpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                string errorMessage = "Delete Error --> "   ex.Message   "  文件名:"   fileName;
                //logger.Error(errorMessage);
                throw;
            }
        }

前台写了三个button,分别进行上传、下载、删除操作:

代码语言:javascript复制
   <StackPanel>
        <Button Name="Upload" Content="FTP 上传"/>
        <Button Name="Download" Content="FTP 下载"/>
        <Button Name="Delete" Content="FTP 删除"/>
    </StackPanel>

后台事件:

代码语言:javascript复制
  public void Upload()
        {
            ftpConfig.IsUpload = true;
            Upload(@"D:temp.png");
            MessageBox.Show("上传完成!!!");
        }

        public void Download()
        {
            Download(@"D:", "temp.png");
            MessageBox.Show("下载完成!!!");
        }

        public void Delete()
        {
            Delete("temp.png");
            MessageBox.Show("删除完成!!!");
        }

公共属性和类的初始化:

代码语言:javascript复制
  private string ftpURI;
        private FTPConfig ftpConfig { get; set; }

        /// <summary>
        ///  连接FTP
        /// </summary>
        /// <param name="ftpConfig"></param>
        public FTPTestViewModel(FTPConfig ftpConfig)
        {
            this.ftpConfig = ftpConfig;
            if (string.IsNullOrEmpty(this.ftpConfig.FtpRemotePath))
            {
                ftpURI = "ftp://"   this.ftpConfig.FtpServerIP   "/";
            }
            else
            {
                ftpURI = "ftp://"   this.ftpConfig.FtpServerIP   "/"   this.ftpConfig.FtpRemotePath   "/";
            }
        }

此外本项目还封装了ftp进行删除文件夹、获取当前目录下明细(包含文件和文件夹)、/ 获取当前目录下文件列表(仅文件)、获取当前目录下所有的文件夹列表(仅文件夹)、判断当前目录下指定的子目录是否存在、判断当前目录下指定的文件是否存在、创建文件夹、获取指定文件大小、改名、 移动文件、切换当前目录、 删除订单目录等方法,这这里不再列举,需要学习的可以下载源码参考。

04—源码下载

链接:https://pan.baidu.com/s/1F7EIi7bOcQVKhlKFFv-uEA

ftp

0 人点赞