C# FTP上传、下载、删除

01FTP概述

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

02效果演示

03代码

先定义配置模型:FTPConfig

 

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上传、下载、删除方法:

 /// <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,分别进行上传、下载、删除操作:

<StackPanel>
        <Button Name="Upload" Content="FTP 上传"/>
        <Button Name="Download" Content="FTP 下载"/>
        <Button Name="Delete" Content="FTP 删除"/>
    </StackPanel>

后台事件:

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("删除完成!!!");
        }

公共属性和类的初始化:

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

技术群:添加小编微信并备注进群

小编微信:dotnet999   

公众号:dotNet编程大全      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值