欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-13 08:01:57
最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下 using...

最近做了一个项目,需要读取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;
     }
   
   }
 }

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