日誌,對程式的排查錯誤很有用處,現寫了一個日誌的類。共用之:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace NetLog
- {
- public static class NetLog
- {
- static string _logFileName = DateTime.Now.Day.ToString() + " Log";
- static string _fileDirectory = System.Environment.CurrentDirectory + "//PQDlog" + "//" + DateTime.Now.Year.ToString()
- + "-" + DateTime.Now.Month.ToString();
- private static void checkPath()
- {
- if (!System.IO.Directory.Exists(_fileDirectory))
- {
- System.IO.Directory.CreateDirectory(_fileDirectory);
- }
- }
- private static void checkFile(string fileName)
- {
- System.IO.StreamWriter sw;
- fileName = _fileDirectory + "//" + fileName+".log";
- if (!System.IO.File.Exists(fileName))
- {
- //如果不存在此檔案,那麼建立它。
- sw= System.IO.File.CreateText(fileName);
- sw.Close();
- }
- }
- public static void WriteLog(string loginfo)
- {
- checkPath();
- checkFile(_logFileName);
- string fileName = _fileDirectory + "//" + _logFileName+".log";
- System.IO.FileStream filestream = new System.IO.FileStream(fileName, System.IO.FileMode.Open| System.IO.FileMode.Create,
- System.IO.FileAccess.Write,System.IO.FileShare.None);
- System.IO.StreamWriter writer = new System.IO.StreamWriter(filestream,System.Text.Encoding.Default);
-
- writer.BaseStream.Seek(0, System.IO.SeekOrigin.End);
-
- writer.WriteLine("{0}--{1}", DateTime.Now.TimeOfDay, loginfo);
- writer.Flush();
- writer.Close();
- filestream.Close();
- }
- /// <summary>
- /// this log's filename.
- /// </summary>
- public static string LogFileName
- {
- get { return _logFileName; }
- set { _logFileName = value; }
- }
- /// <summary>
- /// this log's directory.
- /// </summary>
- public static string FileDirectory
- {
- get { return _fileDirectory; }
- set { _fileDirectory = value; }
- }
- }
- }