FtpHelper implements ftp Server File read/write operations (C #),

Source: Internet
Author: User
Tags ftp file

FtpHelper implements ftp Server File read/write operations (C #),

I recently created a project and needed to read files on the ftp server. So I referred to some help group methods provided on the Internet and encountered some minor details during use, so I made some changes and shared them.

 

 

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:ZOina2017@192.168.10.17/400backup Static private string path = @ "ftp: //" + ConfigurationManager. appSettings ["FtpServerIP"]. toString () + "/"; // target path static private string ftpip = ConfigurationManager. appSettings ["FtpServerIP"]. toString (); // ftp IP address static private string username = ConfigurationManager. appSettings ["FtpUserName"]. toString (); // ftp Username static private string password = ConfigurationManager. appSettings ["FtpPassWord"]. toS Tring (); // ftp password // obtain the file and folder 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); // set the user name and password request. method = WebRequestMethods. ftp. listDirector Y; request. UseBinary = true; request. UsePassive = false; // select active or passive mode. Request. KeepAlive = false; // you must set this attribute. Otherwise, an exception occurs when multiple files are downloaded at a time. 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 files and folders on ftp:" + ex. message); downloadFiles = null; return downloadFiles ;}} /// <summary> /// obtain the file from the ftp server and convert all the content to 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, passw Ord); reqFTP. UsePassive = false; // select active or passive mode. ReqFTP. KeepAlive = false; // you must set this attribute. Otherwise, an exception occurs when multiple files are downloaded at a time. 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 ("failed to get ftp file and read content:" + ex. message); return null ;}/// <summary> /// get the file size /// </ Summary> /// <param name = "file"> relative path of the ip server </param> /// <returns> file size </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); // set the user name and password request. method = WebRequestMetho Ds. ftp. getFileSize; int dataLength = (int) request. getResponse (). contentLength; return dataLength;} catch (Exception ex) {Console. writeLine ("An error occurred while obtaining the file size:" + ex. message); return-1 ;}} /// <summary> /// File Upload /// </summary> /// <param name = "filePath"> original path (absolute path) including file name </param> /// <param name = "objPath"> Target Folder: do not enter the root directory as the relative path of the server </param> public 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 (filePath); using (FileStream fs = fileInfo. openRead () {long length = fs. length; reqFTP = (FtpWebRequest) FtpWebRequest. create (new Uri (url + fileInfo. name); // set the password reqFTP for connecting to FTP. credentials = new NetworkCredential (username, password); // sets whether to keep the connection reqFTP after the request is complete. keepAlive = false; // specifies the execution Line command reqFTP. method = WebRequestMethods. ftp. uploadFile; // specify the data transmission type reqFTP. useBinary = true; using (Stream stream = reqFTP. getRequestStream () {// set the 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 ("File Uploaded successfully") ;}} catch (Exception ex) {Console. writeLine ("failed File Upload error:" + ex. message);} fina Lly {}} catch (Exception ex) {Console. writeLine ("failed File Upload error:" + ex. message);} finally {}} catch (Exception ex) {Console. writeLine ("failed File Upload error:" + ex. message );}} /// <summary> /// delete the file /// </summary> /// <param name = "fileName"> the relative path of the server includes the file name </param> public static void DeleteFileName (string fileName) {try {FileInfo fileInf = new FileInfo (ftpip + "" + fileName); string uri = path + fileName; Ft PWebRequest reqFTP = (FtpWebRequest) FtpWebRequest. create (new Uri (uri); // specify the data transmission type reqFTP. useBinary = true; // The ftp user name and password reqFTP. credentials = new NetworkCredential (username, password); // The default value is true, and the connection will not be closed. // after a command, reqFTP is executed. keepAlive = false; // specifies the command to execute reqFTP. method = WebRequestMethods. ftp. deleteFile; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); response. close ();} catch (Ex Ception ex) {Console. writeLine ("An error occurred while deleting the file:" + ex. message );}} /// <summary> /// the upper level of the new directory must first exist /// </summary> /// <param name = "dirName"> relative path under the server </ param> public static void MakeDir (string dirName) {try {string uri = path + dirName; FtpWebRequest reqFTP = (FtpWebRequest) FtpWebRequest. create (new Uri (uri); // specify the data transmission type reqFTP. useBinary = true; // The ftp user name and password reqFTP. credentials = new NetworkCredential (u Sername, password); reqFTP. method = WebRequestMethods. ftp. makeDirectory; FtpWebResponse response = (FtpWebResponse) reqFTP. getResponse (); response. close ();} catch (Exception ex) {Console. writeLine ("Directory creation error:" + ex. message );}} /// <summary> /// the upper-level directory must exist first /// </summary> /// <param name = "dirName"> relative path under the server </ param> public static void DelDir (string dirName) {try {string uri = path + dirName; Ftp WebRequest 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 ("failed to delete Directory:" + ex. message) ;}/// <summary> /// obtain the folder list from the ftp server /// </sum Mary> /// <param name = "RequedstPath"> relative path under the server </param> /// <returns> </returns> public static List <string> GetDirctory (string RequedstPath) {List <string> strs = new List <string> (); try {string uri = path + RequedstPath; // The target 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. met Hod = 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 ("failed to get directory:" + ex. message);} return strs ;} /// <summary> /// obtain the file list from the ftp server /// </summary> /// <param name = "RequedstPath"> relative path under the server </param> // <returns> </returns> Public static List <string> GetFile (string RequedstPath) {List <string> strs = new List <string> (); try {string uri = path + RequedstPath; // The target 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. G EtResponse (); 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 ("File Retrieval error:" + ex. message) ;}return strs ;}}}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.