File Rename (recursive)

Source: Internet
Author: User

Suppose you need to write to a log file, but you do not want the log file to be too large to affect program performance, you need to rename the original file

Determine if the file is greater than 10M//get the file size if (file.exists (LogPath)) {FileInfo Myfileinfo = n                EW FileInfo (LogPath);                float myfilesize = (float) myfileinfo.length/(1024 * 1024);                if (myFileSize > 10) {//Rename the original file Renamelog (LogPath);  }}//recursive rename private static void Renamelog (String logpath) {String Curpath = System.IO.Path.GetDirectoryName (LogPath);//"d:\ffff\fwww" string curname = System.IO.Path.GetFileNameWithoutEx            Tension (LogPath);//errorlog.txt string curext = System.IO.Path.GetExtension (logpath);//.txt//New file name            int nextnum = 1;            String newstr = "";                try {//determine that the next file does not exist, if present, recursion nextnum = Getpathnum (logpath) + 1;                Newstr = Curpath + "\ \" + removenum (curname) + "_" + Nextnum + curext; If(File.exists (NEWSTR))                {Renamelog (NEWSTR); }} catch {newstr = Curpath + "\ \" + Curname + "_" + guid.newguid () + cur            EXT;            }//Rename method FileInfo fi = new FileInfo (logpath); Fi.        MoveTo (Path.Combine (NEWSTR)); } private static int getpathnum (string pathorname) {try {string Curna                me = System.IO.Path.GetFileNameWithoutExtension (pathorname); if (!curname.                Contains ('_')) {return 0; } return int. Parse (Curname. Split ('_') [Curname. Split ('_').            Count ()-1]);            } catch {return 0;                }}//Remove the name after the number of the private static string Removenum (string name) {try { if (!name. Contains ('_')) {RETurn name; } return name. Substring (0, name. Length-(name. Split ('_') [name. Split ('_'). Count ()-1].            Length + 1));        } catch {return name;} }

Effect:

File Rename (recursive)

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.