FtpHelper实现ftp服务器文件读写操作(C#)

 更新时间:2020年6月25日 11:20  点击:2442

最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Net;
 using System.IO;
 using System.Threading;
using System.Configuration;
 
 namespace FtpSyn
 {
   public class FtpHelper
   {
     //基本设置 ftp://400:ZOina2017@192.168.10.17/400backup
     static private string path = @"ftp://" + ConfigurationManager.AppSettings["FtpServerIP"].ToString() + "/";  //目标路径
     static private string ftpip = ConfigurationManager.AppSettings["FtpServerIP"].ToString();  //ftp IP地址
     static private string username = ConfigurationManager.AppSettings["FtpUserName"].ToString();  //ftp用户名
     static private string password = ConfigurationManager.AppSettings["FtpPassWord"].ToString();  //ftp密码
    
     //获取ftp上面的文件和文件夹
     public static string[] GetFileList(string dir)
     {
       string[] downloadFiles;
       StringBuilder result = new StringBuilder();
       FtpWebRequest request;
       try
       {
         request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir));
         request.UseBinary = true;
         request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
         request.Method = WebRequestMethods.Ftp.ListDirectory;
         request.UseBinary = true;
         request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
         request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
         WebResponse response = request.GetResponse();
         StreamReader reader = new StreamReader(response.GetResponseStream());
 
         string line = reader.ReadLine();
         while (line != null)
         {
           result.Append(line);
           result.Append("\n");
           line = reader.ReadLine();
         }
 
         result.Remove(result.ToString().LastIndexOf('\n'), 1);
         reader.Close();
         response.Close();
         return result.ToString().Split('\n');
       }
       catch (Exception ex)
       {
         LogHelper.writeErrorLog("获取ftp上面的文件和文件夹:" + ex.Message);
         downloadFiles = null;
         return downloadFiles;
       }
     }
 
 
 
 
     /// <summary>
     /// 从ftp服务器上获取文件并将内容全部转换成string返回
     /// </summary>
     /// <param name="fileName"></param>
     /// <param name="dir"></param>
     /// <returns></returns>
     public static string GetFileStr(string fileName, string dir)
     {
       FtpWebRequest reqFTP;
       try
       {
         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + dir + "/" + fileName));
         reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
         reqFTP.UseBinary = true;
         reqFTP.Credentials = new NetworkCredential(username, password);
         reqFTP.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。
         reqFTP.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
         Stream ftpStream = response.GetResponseStream();
         StreamReader reader = new StreamReader(ftpStream);
         string fileStr = reader.ReadToEnd();
 
         reader.Close();
         ftpStream.Close();
         response.Close();
         return fileStr;
       }
       catch (Exception ex)
       {
         LogHelper.writeErrorLog("获取ftp文件并读取内容失败:" + ex.Message);
         return null;
       }
     } 
 
 
     /// <summary>
     /// 获取文件大小
     /// </summary>
     /// <param name="file">ip服务器下的相对路径</param>
     /// <returns>文件大小</returns>
     public static int GetFileSize(string file)
     {
       StringBuilder result = new StringBuilder();
       FtpWebRequest request;
       try
       {
         request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));
         request.UseBinary = true;
         request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
         request.Method = WebRequestMethods.Ftp.GetFileSize;
 
         int dataLength = (int)request.GetResponse().ContentLength;
 
         return dataLength;
       }
       catch (Exception ex)
       {
         Console.WriteLine("获取文件大小出错:" + ex.Message);
         return -1;
       }
     }
 
     /// <summary>
     /// 文件上传
     /// </summary>
     /// <param name="filePath">原路径(绝对路径)包括文件名</param>
     /// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
     public static void FileUpLoad(string filePath,string objPath="")
     {
       try
       {
         string url = path;
         if(objPath!="")
           url += objPath + "/";
         try
         {
 
           FtpWebRequest reqFTP = null;
           //待上传的文件 (全路径)
           try
           {
             FileInfo fileInfo = new FileInfo(filePath);
             using (FileStream fs = fileInfo.OpenRead())
             {
               long length = fs.Length;
               reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
 
               //设置连接到FTP的帐号密码
               reqFTP.Credentials = new NetworkCredential(username, password);
               //设置请求完成后是否保持连接
               reqFTP.KeepAlive = false;
               //指定执行命令
               reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
               //指定数据传输类型
               reqFTP.UseBinary = true;
 
               using (Stream stream = reqFTP.GetRequestStream())
               {
                 //设置缓冲大小
                 int BufferLength = 5120;
                 byte[] b = new byte[BufferLength];
                 int i;
                 while ((i = fs.Read(b, 0, BufferLength)) > 0)
                 {
                   stream.Write(b, 0, i);
                 }
                 Console.WriteLine("上传文件成功");
               }
             }
           }
           catch (Exception ex)
           {
             Console.WriteLine("上传文件失败错误为" + ex.Message);
           }
           finally
           {
 
           }
         }
         catch (Exception ex)
         {
           Console.WriteLine("上传文件失败错误为" + ex.Message);
         }
         finally
         {
 
         }
       }
       catch (Exception ex)
       {
         Console.WriteLine("上传文件失败错误为" + ex.Message);
       }
     }
     
     /// <summary>
     /// 删除文件
     /// </summary>
     /// <param name="fileName">服务器下的相对路径 包括文件名</param>
     public static void DeleteFileName(string fileName)
     {
       try
       {
         FileInfo fileInf = new FileInfo(ftpip +""+ fileName);
         string uri = path + fileName;
         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
         // 指定数据传输类型
         reqFTP.UseBinary = true;
         // ftp用户名和密码
         reqFTP.Credentials = new NetworkCredential(username, password);
         // 默认为true,连接不会被关闭
         // 在一个命令之后被执行
         reqFTP.KeepAlive = false;
         // 指定执行什么命令
         reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
         response.Close();
       }
       catch (Exception ex)
       {
         Console.WriteLine("删除文件出错:" + ex.Message);
       }
     }
     
     /// <summary>
     /// 新建目录 上一级必须先存在
     /// </summary>
     /// <param name="dirName">服务器下的相对路径</param>
     public static void MakeDir(string dirName)
     {
       try
       {
         string uri = path + dirName;
         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
         // 指定数据传输类型
         reqFTP.UseBinary = true;
         // ftp用户名和密码
         reqFTP.Credentials = new NetworkCredential(username, password);
         reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
         response.Close();
       }
       catch (Exception ex)
       {
         Console.WriteLine("创建目录出错:" + ex.Message);
       }
     }
     
     /// <summary>
     /// 删除目录 上一级必须先存在
     /// </summary>
     /// <param name="dirName">服务器下的相对路径</param>
     public static void DelDir(string dirName)
     {
       try
       {
         string uri = path + dirName;
         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
         // ftp用户名和密码
         reqFTP.Credentials = new NetworkCredential(username, password);
         reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
         FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
         response.Close();
       }
       catch (Exception ex)
       {
         Console.WriteLine("删除目录出错:" + ex.Message);
       }
     }
 
     /// <summary>
     /// 从ftp服务器上获得文件夹列表
     /// </summary>
     /// <param name="RequedstPath">服务器下的相对路径</param>
     /// <returns></returns>
     public static List<string> GetDirctory(string RequedstPath)
     {
       List<string> strs = new List<string>();
       try
       {
         string uri = path + RequedstPath;  //目标路径 path为服务器地址
         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
         // ftp用户名和密码
         reqFTP.Credentials = new NetworkCredential(username, password);
         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
         WebResponse response = reqFTP.GetResponse();
         StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
 
         string line = reader.ReadLine();
         while (line != null)
         {
           if (line.Contains("<DIR>"))
           {
             string msg = line.Substring(line.LastIndexOf("<DIR>")+5).Trim();
             strs.Add(msg);
           }
           line = reader.ReadLine();
         }
         reader.Close();
         response.Close();
         return strs;
       }
       catch (Exception ex)
       {
         Console.WriteLine("获取目录出错:" + ex.Message);
       }
       return strs;
     }
 
     /// <summary>
     /// 从ftp服务器上获得文件列表
     /// </summary>
     /// <param name="RequedstPath">服务器下的相对路径</param>
     /// <returns></returns>
     public static List<string> GetFile(string RequedstPath)
     {
       List<string> strs = new List<string>();
       try
       {
         string uri = path + RequedstPath;  //目标路径 path为服务器地址
         FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
         // ftp用户名和密码
         reqFTP.Credentials = new NetworkCredential(username, password);
         reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
         WebResponse response = reqFTP.GetResponse();
         StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
 
         string line = reader.ReadLine();
         while (line != null)
         {
           if (!line.Contains("<DIR>"))
           {
             string msg = line.Substring(39).Trim();
             strs.Add(msg);
           }
           line = reader.ReadLine();
         }
         reader.Close();
         response.Close();
         return strs;
       }
       catch (Exception ex)
       {
         Console.WriteLine("获取文件出错:" + ex.Message);
       }
       return strs;
     }
   
   }
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • C#开发教程之FTP上传下载功能详解

    这篇文章主要为大家详细介绍了C#开发教程之FTP上传下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • C#开发教程之ftp操作方法整理

    这篇文章主要介绍了C#开发教程之ftp操作方法整理的相关资料,需要的朋友可以参考下...2020-06-25
  • c# FTP上传文件实例代码(简易版)

    下面小编就为大家分享一篇c# FTP上传文件的实例代码,超简单哦~希望对大家有所帮助。一起跟随小编过来看看吧,...2020-06-25
  • QT5编译使用QFtp的方法步骤

    这篇文章主要介绍了QT5编译使用QFtp的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-04
  • R语言开发之CSV文件的读写操作实现

    这篇文章主要介绍了R语言开发之CSV文件的读写操作实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-05-06
  • win2008之IIS7中FTP设置技巧

    如果要允许用户在站点中上载或下载文件,就需要在 Web 服务器上设置 FTP。无论站点是位于 Intranet 还是位于 Internet 上,使用 FTP 在所提供的位置中上载和下载文件的原理是相同的。...2016-01-27
  • C#开发windows服务实现自动从FTP服务器下载文件

    这篇文章主要为大家详细介绍了C#开发windows服务实现自动从FTP服务器下载文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • FtpHelper实现ftp服务器文件读写操作(C#)

    这篇文章主要为大家详细介绍了FtpHelper实现ftp服务器文件读写操作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • ruby ftp封装实例详解

    这篇文章主要介绍了ruby ftp封装实例详解的相关资料,需要的朋友可以参考下...2020-06-30
  • Java使用Sftp和Ftp实现对文件的上传和下载

    这篇文章主要介绍了Java使用Sftp和Ftp实现对文件的上传和下载,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-25
  • C++文件读写代码分享

    本文给大家分享的是2个C++实现文件读写的代码,都非常的简单实用,有需要的小伙伴可以参考下。...2020-04-25
  • C#利用SFTP实现上传下载

    这篇文章主要为大家详细介绍了C#利用SFTP实现上传下载的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • windows 2003服务器安装 IIS6.0和IIS自带FTP服务器图文教程

    这篇文章主要介绍了windows 2003服务器安装 IIS6.0和IIS自带FTP服务器图文教程,需要的朋友可以参考下...2016-01-27
  • c#保存窗口位置大小操作类(序列化和文件读写功能)

    这篇文章主要介绍了c#保存窗口位置大小操作类,其实就是把序列化和文件读写合到一块,大家参考使用...2020-06-25
  • 关于C#连接FTP时路径问题的解决方法

    最近在工作中遇到一个需求,需要利用C#连接FTP,在连接过程中遇到一个问题,所以下面这篇文章主要给大家介绍了关于C#连接FTP时路径问题的解决方法,需要的朋友可以参考借鉴,下面来一起看看吧。...2020-06-25
  • java读取ftp中TXT文件的案例

    这篇文章主要介绍了java读取ftp中TXT文件的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-24
  • PHP中文件读写操作

    PHP中文件读写操作   PHP中提供了一系列的I/O函数,能简捷地实现我们所需要的功能,包括文件系统操作和目录操作(如“复制[copy]”)。下面给大家介绍的是基本...2016-11-25
  • 详解python中的异常和文件读写

    这篇文章主要介绍了python中的异常和文件读写的的相关资料,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下...2021-01-03
  • c# 共享状态的文件读写实现代码

    开发中有时会遇到要对文件进行共享状态的读写操作,代码如下,需要的朋友可以参考下...2020-06-25
  • C#控制台进行文件读写的方法

    这篇文章主要介绍了C#控制台进行文件读写的方法,涉及C#操作文件读写的相关技巧,非常具有实用价值,需要的朋友可以参考下...2020-06-25