Log in to save C # program

  Dangdang Dangdang, I'm here again, this one can insert code - this time on Log saved, will be saved into the relevant operational messages to txt file named with the date.

  1. Create a new folder in the Log perform directory.

   String filePath System.AppDomain.CurrentDomain.BaseDirectory + = " Log " ;    // AppDomain.CurrentDomain.BaseDirectory program to acquire the group directory, directory group plus Log Log path is

  IF Directory.CreateDirectory (filePath) (Directory.Exists (filePath)!);    // If the path does not exist, create this path (that is, the base directory under the program did not create the Log Log folder when the folder)

  2. Establish date txt file named in the Log folder, and the corresponding information is written to this txt file. 

  String LogPath = filePath + " \\ " + DateTime.Now.ToString ( " YYYY-the MM-dd " ) + " .txt " ;    // TXT file path plus \ xxxx-xxxx folder path after Log .txt, the first "\" as an escape character.

  try

  {

    a using (StreamWriter sw = File.AppendText (LogPath)    // Open the file and prepare written information

    {

      sw.WriteLine (DateTime.Now.ToString ( " HH: mm: SS " ) + " want to save operation information " );    // write information corresponding to the current time +

    }

  }

  the catch (Exception EX)    // anomalies appear in the process of writing log

  {

    MessageBox.Show (DateTime.Now.ToString ( " HH: mm: SS " ) + " write the log failure " ,   " error "   );    // jump MessageBox, an error message is displayed, and indicate a failure to write the log 

  }

  3. periodically clear: log files every seven days will be full 7 days prior to the log file cleared.

String [] = the Directory.GetFiles Files (filePath, " * .txt " );   // all Log information array txt file folder under 
the foreach ( var File in Files)   // each txt file 
{
    Fi FileInfo = new new FileInfo (File);   // a new new FileInfo object Fi
     IF ((the DateTime.Now-fi.CreatTime) .TotalDays> . 7 ) fi.Delete ();   // if the current time minus the time of creation of the file txt greater than 7, this txt file to delete 
    the else  BREAK ;
}

  Simply run the program information stored log above, the method is not limited to this kind of, you can find online, try.

    

Guess you like

Origin www.cnblogs.com/kigila/p/11777937.html