C# FTP上传和下载文件操作

   我们使用C# 需要通过FTP访问服务器时,那么上位机就要作为客户端,通过连接FTP服务来上传下载文件。这里用实际代码和简要的文字描述一下。


1、初始化FTP

   见代码描述段中的构造函数 FtpOperation(),在初始化类的同时将用户各个参数初始化。
   首先,将服务器IP传递过来,这个是第一重要的。其次,将用户ID、密码以及路径信息获取。最后,将其它参数赋初值。


2、上传文件

   上传文件,即,将本地的文件拷贝到服务器上。封装了的接口DoUpload(),调用之前要陪将对应的本地路径参数获取赋值,这里为一个全路径参数。

参考上传实现函数
private void UploadFile(string FileName)


3、下载文件

   下载文件,即,将服务器上的文件拷贝到本地。封装了的接口DoDownload(),调用之前要陪将对应的本地路径参数获取赋值,这里包括要下载的文件名以及本地全路径名。

参数看下载实现函数
public void DownloadFile(string FileName, string LocalSavePath)


4、代码描述


 class FtpOperation
 {
        private string ftpServerIP;//服务器IP
        private string ftpRemotePath;//服务器路径
        private string ftpUserID;//用户
        private string ftpPassword;//密码
        private string ftpURI;//FTP服务器的全路径
        private int BUF_SIZE;//文件缓存大小
        public string ftp_local_path;//本地全路径        
        public string ftp_local_name;//本地文件名称
        public bool error_state;//错误状态

        /// <summary>
        /// 初始化FTP
        /// </summary>
        /// <param name="FtpServerIP">FTP连接地址</param>
        public FtpOperation(string ServerIP)
        {
            ftpServerIP = ServerIP;
            ftpRemotePath = "";
            ftpUserID = "ftpuser";
            ftpPassword = "pswd";
            ftpURI = "ftp://" + ftpServerIP + ftpRemotePath + "/";
            ftp_local_path = "";
            ftp_local_name = "";
            error_state = false;
        }
                 

        /// <summary>
        /// 上传接口
        /// </summary>
        public void DoUpload()
        {
            UploadFile(ftp_local_path);
        }

        /// <summary>
        /// 下载接口
        /// </summary>
        public void DoDownload()
        {
            DownloadFile(ftp_local_name, ftp_local_path);
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="filename">文件名</param>
        private void UploadFile(string FileName)
        {
            FileInfo fileInfo = new FileInfo(FileName);
            string uri = ftpURI + fileInfo.Name;//目标文件路径            
            FtpWebRequest reqFTP;//请求参数
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));//创建FTP请求
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//网络凭证
            reqFTP.KeepAlive = false;//使用后断开
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//上传模式
            reqFTP.UseBinary = true;//二进制数据
            //reqFTP.UsePassive = false;//是否监听连接
            reqFTP.ContentLength = fileInfo.Length;//文件大小
            BUF_SIZE = (int)fileInfo.Length;//文件buf大小
            reqFTP.Timeout = 30000;//超时ms 
            byte[] buff = new byte[BUF_SIZE];//新建buf字符空间
            int ContentLength;
            FileStream fs = fileInfo.OpenRead();//建读数据流
            try
            {
                Stream strm = reqFTP.GetRequestStream();//上传数据
                ContentLength = fs.Read(buff, 0, BUF_SIZE);//读内容长度
                while (ContentLength != 0)
                {
                    strm.Write(buff, 0, ContentLength);
                    ContentLength = fs.Read(buff, 0, BUF_SIZE);
                }
                //关闭
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                error_state = true;
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="LocalSavePath">本地文件路径</param>
        /// <param name="fileName">服务端文件名</param>
        public void DownloadFile(string FileName, string LocalSavePath)
        {
            FtpWebRequest reqFTP;
            try
            {
                FileStream outputStream = new FileStream(LocalSavePath, FileMode.Create);//本地输出流
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpUserID + ":" + ftpPassword + "@" + ftpServerIP + "/" + FileName));//创建FTP请求
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;//下载
                reqFTP.UseBinary = true;//二进制
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//网络凭证
                //reqFTP.UsePassive = false;//是否监听连接
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();//响应服务器
                Stream ftpStream = response.GetResponseStream();//响应数据流 
                BUF_SIZE = (int)response.ContentLength;//数据大小             
                int readCount;
                byte[] buffer = new byte[BUF_SIZE];
                readCount = ftpStream.Read(buffer, 0, BUF_SIZE);//读取数据流
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, BUF_SIZE);
                }
                //关闭
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                error_state = true; 
                MessageBox.Show(ex.Message);
            }
        }
    }
  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

火星papa

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

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

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

打赏作者

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

抵扣说明:

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

余额充值