C#FTP对文件的操作


一、FTP是什么?

FTP是用来在两台计算机之间传输文件

二、FTP文件操作

1.Ftp数据加载

代码如下(示例):

/// <summary>
/// Ftp数据加载
/// </summary>
/// <param name="F_Ftp">FTP服务器IP</param>
/// <param name="F_User">FTP登录帐号</param>
/// <param name="F_Pwd">FTP登录密码</param>
public void GetFtpFiles(string F_Ftp,string F_User,string F_Pwd)
{
    //FTP请求对象
    FtpWebRequest request = null;
    //FTP响应
    FtpWebResponse ftpResponse = null;

    //FTP响应流
    StreamReader reader = null;

    try
    {
       //声明集合接收FTP里面的文件
       //FtpFiles为两个属性,Type, Name
        List<FtpFiles> list = new List<FtpFiles>();
        //声明uri请求格式

        string uri = string.Format("ftp://{0}", F_Ftp);


        //生成FTP请求
        request = (FtpWebRequest)WebRequest.Create(new Uri(uri));
        //FTP登录  账号&密码
        request.Credentials = new NetworkCredential(F_Pwd, F_User);
         //设置FTP方法
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        request.UsePassive = false;
        //生成FTP响应
        ftpResponse = (FtpWebResponse)request.GetResponse();

        //FTP响应流
        reader = new StreamReader(ftpResponse.GetResponseStream());

        string line = reader.ReadLine();

        while (line != null)
        {
             //判断是文件夹
              if (line.Contains("<DIR>"))
              {
                //截取字符串
                 string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                 FtpFiles ftpFiles = new FtpFiles();
                 ftpFiles.type = "[文件夹]";
                 ftpFiles.Name = msg;

                 list.Add(ftpFiles);
               }
               //否则是文件
               else
               {
                  string msg = line.Substring(39).Trim();
                  FtpFiles ftpFiles = new FtpFiles();
                  ftpFiles.type = "[文  件]";
                  ftpFiles.Name = msg;

                  list.Add(ftpFiles);
                }
                    line = reader.ReadLine();
        }

        //将数据绑定dataGridView1
        dataGridView1.DataSource = list;
        dataGridView1.AutoGenerateColumns = false;     

}
catch (Exception ex)
{
        MessageBox.Show("登录或链接失败!请检查FTP地址,用户名与密码");

}
finally {
        //关闭流
        if (reader!=null)
        {
              reader.Close();
        }
        if (ftpResponse!=null)
        {
              ftpResponse.Close();
        }
                    
  }
          
}

2.Ftp文件上传

代码如下(示例):

/// <summary>
/// FTP上传文件
/// </summary>
/// <param name="ftpServerIP">FTP服务器IP</param>
/// <param name="ftpUserID">FTP登录帐号</param>
/// <param name="ftpPassword">FTP登录密码</param>
/// <param name="filename">上文件文件名(绝对路径)</param>
  public void FTPUploadFile(string ftpServerIP, string ftpUserID, string ftpPassword, string filename)
{
     //上传文件
     FileInfo uploadFile = null;

      //上传文件流
      FileStream uploadFileStream = null;

       //FTP请求对象
       FtpWebRequest ftpRequest = null;

       //FTP流
       Stream ftpStream = null;

            try
            {
                //获取上传文件
                uploadFile = new FileInfo(filename);

                //创建FtpWebRequest对象
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + uploadFile.Name));

                //FTP登录
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                ftpRequest.KeepAlive = false;

                //FTP请求执行方法
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                // 指定数据传输类型
                ftpRequest.UseBinary = true;

                // 上传文件时通知服务器文件的大小
                ftpRequest.ContentLength = uploadFile.Length;

                // 缓冲大小设置为2kb
                int buffLength = 2048;

                byte[] buff = new byte[buffLength];
                int contentLen;

                // 打开一个文件流读上传的文件
                uploadFileStream = uploadFile.OpenRead();

                // 把上传的文件写入流
                ftpStream = ftpRequest.GetRequestStream();

                // 每次读文件流的2kb
                contentLen = uploadFileStream.Read(buff, 0, buffLength);

                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    ftpStream.Write(buff, 0, contentLen);

                    contentLen = uploadFileStream.Read(buff, 0, buffLength);
                }

                MessageBox.Show("上传成功");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (uploadFileStream != null)
                {
                    uploadFileStream.Close();
                }

                if (ftpStream != null)
                {
                    ftpStream.Close();
      	}
}

3.Ftp文件下载

/// <summary>
/// FTP下载文件
/// </summary>
/// <param name="ftpServerIP">FTP服务器IP</param>
/// <param name="ftpUserID">FTP登录帐号</param>
/// <param name="ftpPassword">FTP登录密码</param>
/// <param name="saveFilePath">保存文件路径</param>
/// <param name="saveFileName">//保存文件名</param>
/// <param name="downloadFileName">下载文件名</param>

        public void FTPDownLoadFile(string ftpServerIP, string ftpUserID, string ftpPassword,string saveFilePath, string saveFileName, string downloadFileName) {
            //定义FTP请求对象
            FtpWebRequest ftpRequest = null;
            //定义FTP响应对象
            FtpWebResponse ftpResponse = null;

            //存储流
            FileStream saveStream = null;
            //FTP数据流
            Stream ftpStream = null;

            try
            {
                //生成下载文件
                saveStream = new FileStream(saveFilePath + "\\" + saveFileName,FileMode.Create);

                //生成FTP请求对象                                         
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + downloadFileName));

                //设置下载文件方法
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                //设置文件传输类型
                ftpRequest.UseBinary = true;

                //设置登录FTP帐号和密码
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                //生成FTP响应对象
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                //获取FTP响应流对象
                ftpStream = ftpResponse.GetResponseStream();

                //响应数据长度
                long cl = ftpResponse.ContentLength;

                int bufferSize = 2048;

                int readCount;

                byte[] buffer = new byte[bufferSize];

                //接收FTP文件流
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                while (readCount > 0)
                {
                    saveStream.Write(buffer, 0, readCount);

                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                MessageBox.Show("下载成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }

                if (saveStream != null)
                {
                    saveStream.Close();
                }

                if (ftpResponse != null)
                {
                    ftpResponse.Close();
                }
            }


        }

4.Ftp文件删除

/// <summary>
/// 
/// </summary>
/// <param name="ftpServerIP">FTP服务器IP</param>
/// <param name="ftpUserID">FTP登录帐号</param>
/// <param name="ftpPassword">FTP登录密码</param>
/// <param name="filename">删除文件名(路径)</param>

        public void DeleteFtp(string ftpServerIP, string ftpUserID, string ftpPassword, string filename) {

            string uri = "ftp://"+ftpServerIP + "/" + filename;

            //定义FTP请求对象
            FtpWebRequest ftpRequest = null;
            //定义FTP响应对象
            FtpWebResponse ftpResponse = null;

            //FTP数据流
            Stream ftpStream = null;

            try
            {

                //生成FTP请求对象                                         
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));


                //设置登录FTP帐号和密码
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                ftpRequest.KeepAlive=false;

                //设置删除文件方法
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;



                //生成FTP响应对象
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                //获取FTP响应流对象
                ftpStream = ftpResponse.GetResponseStream();


            
                MessageBox.Show("删除成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }

                if (ftpResponse != null)
                {
                    ftpResponse.Close();
                }
            }

           
            
        
        }

项目演示:

这是自己写的一个串口演示的小Demo,仅供参考

C# WinForm 实现FTP对文件的:添加、删除、下载

👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

孙筱北

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

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

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

打赏作者

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

抵扣说明:

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

余额充值