"C #" Ftphelper An example of a read and write operation to a server file

Source: Internet
Author: User
Tags ftp file
This article is mainly for you to introduce the Ftphelper implementation of FTP server file read and write operations, with a certain reference value, interested in small partners can refer to

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 () + "/"; 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 above files and folders 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 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>////Retrieve 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 Stati       C string Getfilestr (String fileName, string dir) {FtpWebRequest 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 &GT;IP server < /param>//<returns> file size </returns> public static int GetFileSize (string file) {Stringbu       Ilder 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= "FilePath" > Original path (absolute path) including file name </p  aram>//<param name= "Objpath" > Destination folder: The relative path under the server is not filled with the root directory </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 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; Specify execution Command Reqftp.method = webrequestmethods.ftP.uploadfile;                Specifies the data transfer type reqftp.usebinary = TRUE; using (Stream stream = Reqftp.getrequeststream ()) {//Set buffer size int Bufferlengt                 h = 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 ("The Upload file failed error is" + ex.)           Message); } finally {}} catch (Exception ex) {Console.WriteLine ( "Upload file failed error is" + ex.         Message); } finally {}} catch (Exception ex) {Console.WriteLine ("Upload file failed error =" + Ex.       Message); }}///<summary>//delete files//</summary>//<param name= relative path under "filename" > Server includes 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//After a command is executed 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>//<param name= "DirName" > Service Relative path under the device </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>//<param name= "DirName" > Service Relative path under the device </param> public static void Deldir (string dirName) {try {string uri = path + di         Rname;         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 name= "Requedstpath" Relative path under Server </param>///<returns></returns> public static list<string> getdirctory (String R       Equedstpath) {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 = newStreamReader (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= "Requedstpath" > Server phase On path </param>///<returns></returns> public static list<string> GetFile (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; }      } }
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.