C#使用ftp进行文件上传和下载功能(二)

上一篇主要讲解FTP服务器的搭建,本节话不多说直接撸码:

1.首先ftp需要有ip和port,以及登录用户等信息,因此创建三个属性;

        /// <summary>
        /// FTP的服务器地址,格式为ftp://192.168.1.234:8021/。
        /// </summary>
        private string FTPCONSTR { get; set; }
        /// <summary>
        /// //FTP服务器的用户名
        /// </summary>
        private string FTPUSERNAME { get; set; }
        /// <summary>
        /// //FTP服务器的密码
        /// </summary>
        private string FTPPASSWORD { get; set; }

2.构造函数:

public FtpHhelper(string ip, string username, string password, string port = "8090")
        {
            FTPCONSTR = string.Format("{0}://{1}:{2}/", "ftp", ip, port);
            FTPUSERNAME = username;
            FTPPASSWORD = password;
        }

3.文件上传方法:

#region 本地文件上传到FTP服务器
        /// <summary>
        /// 本地文件上传到FTP服务器
        /// </summary>
        /// <param name="path">本地的文件目录</param>
        /// <param name="name">文件名称</param>
        /// <returns></returns>
        public bool UploadFile(string path, string name)
        {
            FileInfo f = new FileInfo(path);
            path = FTPCONSTR + name;//这个路径是我要传到ftp目录下的这个目录下
            FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
            reqFtp.UsePassive = false;//只需要添加这一句话
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
            reqFtp.KeepAlive = false;
            reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
            reqFtp.ContentLength = f.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = f.OpenRead();
            try
            {
                Stream strm = reqFtp.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

4.文件下载方法:

 #region FTP服务器文件下载到本地
        /// <summary>
        /// FTP服务器文件下载到本地
        /// </summary>
        /// <param name="ftpfileparh"></param>
        /// <param name="targetpath"></param>
        /// <returns></returns>
        private bool DownLoad(string ftpfileparh, string targetpath)
        {
            bool res;
            try
            {
                FileStream outputStream = new FileStream(targetpath, FileMode.Create);
                FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpfileparh));
                downRequest.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
                downRequest.Timeout = 10000;
                //设置要发送到FTP服务器的命令
                downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                downRequest.KeepAlive = true;
                //应对ftp下载文件超时处理代码,待测试
                downRequest.ServicePoint.Expect100Continue = false;//ftp下载文件时超时处理,继续重新处理
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                downRequest.CachePolicy = noCachePolicy;//清理缓存数据
                //
                FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long c1 = response.ContentLength;
                int bufferSize = 65536;
                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 e)
            {
                return false;
            }
            return true;
        }
        #endregion

5.方法调用示例:
    /// 
    /// 
    ///上传文件用法
    ///string ftpIP = "192.168.71.249";
    ///string ftpPort = "65501";
    ///string ftpUserName = "zy02";
    ///string ftpPassword = "HYtx@2024";
    ///string localPath = "D:\\BLL-0001-PZ.pdf";
    ///string remotePath = "/BLL-0001-PZ.pdf";
    ///FTPHelper FTPHelper = new FTPHelper(ftpIP, ftpUserName, ftpPassword, ftpPort);
    ///bool uploadresult = FTPHelper.UploadFile(localPath, remotePath);
    /// 
    /// 
    /// 
    /// 下载文件用法
    /// //存储临时文件位置
    /// string filePath = @"D:\Users\" + ip;
    /// //加工程序文件
    /// string sourceFile = @"ftp://" + ip;
    /// DownLoad(sourceFile+"/"+ proname + ".ini", filePath + "\\" + proname + ".ini");//下载加工文件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A_nanda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值