Recently done a project, need to read the files on the FTP server, so refer to some of the online Help group method, the use of the process, there are some small details, so I made some changes, to share
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 {//Basic settings Ftp://400:[email protected]/400backup STA Tic private string path = @ "ftp://" + configurationmanager.appsettings["Ftpserverip"]. ToString () + "/"; Destination path static private string Ftpip = configurationmanager.appsettings["Ftpserverip"]. ToString (); FTP IP address static private string username = configurationmanager.appsettings["FtpUserName"]. ToString (); FTP user name static private string password = configurationmanager.appsettings["FTPPassword"]. ToString (); FTP Password//Get FTP files and folders above public static string[] Getfilelist (string dir) {Strin G[] 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);//set user name and password request. Method = WebRequestMethods.Ftp.ListDirectory; Request. Usebinary = true; Request. Usepassive = false; Choose active or passive mode, this sentence should be added. Request. KeepAlive = false;//Be sure to set this property, otherwise the exception occurs when multiple files are downloaded at once. 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 ("Get FTP Files and folders above:" + ex.) Message); Downloadfiles = null; return downloadfiles; }}///<summary>///Get the files from the FTP server and convert all the contents to a string return///</summary>// <param name= "FileName" ></param>//<param name= "dir" ></param>//<returns> ;</returns> public static string Getfilestr (String fileName, string dir) {Ftpwebreques T reqftp; try {reqftp = (ftpwebrequest) ftpwebrequest.create (The new Uri (path + dir + "/" + FileName)); Reqftp.method = WebRequestMethods.Ftp.DownloadFile; Reqftp.usebinary = true; Reqftp.credentials = new NetworkCredential (username, password); reqftP.usepassive = false; Choose active or passive mode, this sentence should be added. Reqftp.keepalive = false;//Be sure to set this property, otherwise the exception occurs when multiple files are downloaded at once. 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 ("Get FTP file and read content failed:" + ex. Message); return null; }}///<summary>//Get file Size///</summary>//<param name= "file Relative path under >IP server </param>////<returns> file size </returns> public static int GetFileSize (Strin G 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);//set user name and password request. Method = WebRequestMethods.Ftp.GetFileSize; int datalength = (int) request. GetResponse (). ContentLength; return datalength; } catch (Exception ex) {Console.WriteLine ("Get File Size error:" + ex.) Message); return-1; }}///<summary>//File upload///</summary>//<param name= "Filepat H "> Original path (absolute path) includes file name </param>//<param name=" Objpath "> Destination folder: Relative path under server is not filled with root directory </param> PU Blic static void FileUpLoad (String filepath,string objpath= "") {try {sTring url = path; if (objpath!= "") URL + = Objpath + "/"; try {ftpwebrequest reqftp = null; File to be uploaded (full path) try {FileInfo FileInfo = new FileInfo (file Path); using (FileStream fs = Fileinfo.openread ()) {Long length = fs. Length; Reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (URL + fileinfo.name)); Set the password for the account connected to ftp Reqftp.credentials = new NetworkCredential (username, password); Sets whether to maintain a connection after the request is complete reqftp.keepalive = false; Specifies the execution command reqftp.method = WebRequestMethods.Ftp.UploadFile; Specify the data Transfer type reqFtp.usebinary = true; using (Stream stream = Reqftp.getrequeststream ()) {//Set buffer size 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 ("Upload file succeeded"); }}} catch (Exception ex) { Console.WriteLine ("Upload file failed error is" + ex.) Message); } finally {}} catch (Except Ion ex) { Console.WriteLine ("Upload file failed error is" + ex.) Message); } finally {}} catch (Exception ex) {Console.WriteLine ("Upload file failed error is" + ex.) Message); }}///<summary>//delete files///</summary>//<param name= Relative paths under "filename" > server include file name </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)); Specifies the data transfer type reqftp.usebinary = TRUE; FTP user name and password reqftp.credentials = new NetworkCredential (username, password); The default is true, the connection is not closed//executed after a command Reqftp.keePalive = false; Specifies what command to execute Reqftp.method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Response. Close (); } catch (Exception ex) {Console.WriteLine ("Error Deleting file:" + ex.) Message); }}///<summary>//New directory must first exist///</summary>//<PA Ram name= relative path under "DirName" > Server </param> public static void MakeDir (string dirName) {try {string uri = path + dirName; FtpWebRequest reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (URI)); Specifies the data transfer type reqftp.usebinary = TRUE; FTP user name and password reqftp.credentials = new NetworkCredential (username, password); Reqftp.method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Response. Close (); } catch (Exception ex) {Console.WriteLine ("Error creating directory:" + ex.) Message); }}///<summary>///delete directory must first exist///</summary>//<PA Ram name= relative path under "DirName" > Server </param> public static void Deldir (string dirName) {try {string uri = path + dirName; FtpWebRequest reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (URI)); FTP user name and password reqftp.credentials = new NetworkCredential (username, password); Reqftp.method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (ftpwebresponse) reqftp.getresponse (); Response. Close (); } catch (Exception ex) { Console.WriteLine ("Error deleting directory:" + ex.) Message); }}///<summary>///Get a list of folders from the FTP server///</summary>/<param NA Me= relative paths under "Requedstpath" > Servers </param>//<returns></returns> public static LIST<STR Ing> getdirctory (String requedstpath) {list<string> STRs = new list<string> (); try {string uri = path + Requedstpath; The destination path is the server address ftpwebrequest reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (URI)); FTP user name and password reqftp.credentials = new NetworkCredential (username, password); Reqftp.method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = Reqftp.getresponse (); StreamReader reader = new StreamReader (response. GetResponseStream ());//Chinese file name 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 ("Get directory Error:" + ex.) Message); } return STRs; }///<summary>///Get a list of files from the FTP server///</summary>//<param name= "requeds Tpath "> Relative path under Server </param>//<returns></returns> public static list<string> Get File (String requedstpath) {list<string> STRs = new list<string> (); try { String uri = path + Requedstpath; The destination path is the server address ftpwebrequest reqftp = (ftpwebrequest) ftpwebrequest.create (new Uri (URI)); FTP user name and password reqftp.credentials = new NetworkCredential (username, password); Reqftp.method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = Reqftp.getresponse (); StreamReader reader = new StreamReader (response. GetResponseStream ());//Chinese file name 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 ("Get File Error:" + ex.) Message); } return STRs; } } }
Ftphelper implementing FTP Server file read and write operations (C #)