C#FTP对文件的操作

文章目录

  • 一、FTP是什么?
  • 二、FTP文件操作
    • 1.Ftp数据加载
    • 2.Ftp文件上传
    • 3.Ftp文件下载
    • 4.Ftp文件删除
  • 项目演示:


一、FTP是什么?

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

二、FTP文件操作

1.Ftp数据加载

代码如下(示例):

/// 
/// Ftp数据加载
/// 
/// FTP服务器IP
/// FTP登录帐号
/// FTP登录密码
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(""))
              {
                //截取字符串
                 string msg = line.Substring(line.LastIndexOf("") + 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文件上传

代码如下(示例):

/// 
/// FTP上传文件
/// 
/// FTP服务器IP
/// FTP登录帐号
/// FTP登录密码
/// 上文件文件名(绝对路径)
  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文件下载

/// 
/// FTP下载文件
/// 
/// FTP服务器IP
/// FTP登录帐号
/// FTP登录密码
/// 保存文件路径
/// //保存文件名
/// 下载文件名

        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文件删除

/// 
/// 
/// 
/// FTP服务器IP
/// FTP登录帐号
/// FTP登录密码
/// 删除文件名(路径)

        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对文件的:添加、删除、下载

你可能感兴趣的:(C#_Winform,c#,开发语言,winform,ftp)