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)