C # FTP Determines whether a directory exists and creates folders

Source: Internet
Author: User
Tags first string ftp connection

Work in the project has been using the FTP upload log file problems, the new server is set up, the log can not be uploaded. Just to learn about FTP.

The process in the program is, a timer, every minute to detect the configuration file in the local log file path has no log files, if any, upload to the server, and then delete the local files. The logs are in a date, a folder per day, followed by a log type, grouped by type. Detects if the folder exists on the server before uploading and creates a file if it does not exist.

Here is the code. (FTP-only part)

/// <summary>        ///determine if a file's directory is stored, not saved, or created/// </summary>        /// <param name= "Destfilepath" >Local Files directory</param>         Public voidCheckDirectoryAndMakeMyWilson3 (stringDestfilepath) {            stringFulldir = Destfilepath.indexof (':') >0? Destfilepath.substring (Destfilepath.indexof (':') +1): Destfilepath; Fulldir= Fulldir.replace ('\\','/'); string[] dirs = Fulldir.split ('/');// parse out all the filenames on the path stringCurDir ="/";  for(inti =0; I < dirs. Length; i++)// loop through each folder {if(Dirs[i] = ="")Continue; stringDIR =Dirs[i]; //if it is a/start path, the first one is empty                if(dir! =NULL&& dir. Length >0)                {                    Try{CheckDirectoryAndMakeMyWilson2 (CurDir, dir); CurDir+ = dir +"/";                    }                    Catch(Exception) {}}} }
 Public void CheckDirectoryAndMakeMyWilson2 (stringstring  remotedirname)        {            if (!  Directoryexist (RootDir, Remotedirname))//Determine if the directory under the current directory has                 "\ \" + remotedirname);        }
/// <summary>        ///determine if the subdirectory specified in the current directory exists/// </summary>        /// <param name= "Remotedirectoryname" >The specified directory name</param>         Public BOOLDirectoryexist (stringRootDir,stringremotedirectoryname) {            string[] Dirlist =getdirectorylist (RootDir);// Get subdirectories if(Dirlist.length >0)            {                foreach(stringStrinchdirlist) {                    if(str. Trim () = =Remotedirectoryname.trim ()) {                        return true; }                }            }            return false; }
//Get subdirectories         Public string[] Getdirectorylist (stringdirName) {            string[] Drectory =getfilesdetaillist (dirName); List<string> strlist =Newlist<string>(); if(Drectory. Length >0)            {                foreach(stringStrinchdrectory) {                    if(str. Trim (). Length = =0)                        Continue; //there will be two formats for more information to return//one containing <DIR>//A first string is a permission action symbol such as DRWXERWXX//now write the code to contain the strings in both formats                    if(str. Trim (). Contains ("<DIR>") {strlist.add (str). Substring ( the).                    Trim ()); }                    Else                    {                        if(str. Trim (). Substring (0,1). ToUpper () = ="D") {Strlist.add (str. Substring ( -).                        Trim ()); }                    }                }            }            returnStrlist.toarray (); }
/// <summary>        ///Get Clear Documentation/// </summary>        /// <param name= "path" ></param>        /// <returns></returns>         Public string[] Getfilesdetaillist (stringpath) {            returnGetfilelist ("ftp://"+ Ftpserverip +"/"+path, WebRequestMethods.Ftp.ListDirectoryDetails); }
//all Call this//The above code example demonstrates how to get a list of files from an FTP server        Private string[] Getfilelist (stringPathstringwrmethods) {StringBuilder result=NewStringBuilder (); Try{Connect (path);// Establish FTP connection Reqftp.method=Wrmethods; Reqftp.keepalive=false; WebResponse response=Reqftp.getresponse (); StreamReader Reader=NewStreamReader (response. GetResponseStream (), System.Text.Encoding.Default);//Chinese file name                stringline =Reader.                ReadLine ();  while(Line! =NULL) {result.                    Append (line); Result. Append ("\ n"); Line=Reader.                ReadLine (); }                //To remove the trailing ""                if(result.) ToString ()! ="") {result. Remove (result. ToString (). LastIndexOf ("\ n"),1); } reader.                Close (); Response.                Close (); returnResult. ToString (). Split ('\ n'); }            Catch(Exception ex) {Throw NewException ("failed to get list of files. Reason:"+Ex.            Message); }        }
//Connect to FTP        Private voidConnect (String path) {//to create a FtpWebRequest object from a URIReqftp = (ftpwebrequest) ftpwebrequest.create (NewUri (path)); //specifying data Transfer TypesReqftp.method =System.Net.WebRequestMethods.Ftp.UploadFile; Reqftp.usebinary=true; Reqftp.usepassive=false;// Indicates the connection type is active mode //FTP user name and passwordReqftp.credentials =NewNetworkCredential (Ftpuserid, FTPPassword); }
/// <summary>        ///Create a directory/// </summary>        /// <param name= "DirName" ></param>         Public voidMakeDir (stringdirName) {            Try            {                stringURI ="ftp://"+ Ftpserverip +"/"+DirName; Connect (URI);//ConnectionReqftp.method =WebRequestMethods.Ftp.MakeDirectory; Reqftp.keepalive=false; FtpWebResponse Response=(FtpWebResponse) reqftp.getresponse (); Response.            Close (); }            Catch(Exception ex) {Throw NewException ("failed to create file because:"+Ex.            Message); }        }

C # FTP Determines whether a directory exists and creates folders

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.