Log.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.IO;
  6. namespace Common
  7. {
  8. /// <summary>
  9. /// 日志类
  10. /// </summary>
  11. public class Log
  12. {
  13. private string logFile;
  14. private StreamWriter writer;
  15. private FileStream fileStream = null;
  16. public Log(string fileName)
  17. {
  18. logFile = fileName;
  19. CreateDirectory(logFile);
  20. }
  21. public void log(string info)
  22. {
  23. try
  24. {
  25. System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
  26. if (!fileInfo.Exists)
  27. {
  28. fileStream = fileInfo.Create();
  29. writer = new StreamWriter(fileStream);
  30. }
  31. else
  32. {
  33. fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
  34. writer = new StreamWriter(fileStream);
  35. }
  36. writer.WriteLine(DateTime.Now + ": " + info);
  37. }
  38. finally
  39. {
  40. if (writer != null)
  41. {
  42. writer.Close();
  43. writer.Dispose();
  44. fileStream.Close();
  45. fileStream.Dispose();
  46. }
  47. }
  48. }
  49. public void CreateDirectory(string infoPath)
  50. {
  51. DirectoryInfo directoryInfo = Directory.GetParent(infoPath);
  52. if (!directoryInfo.Exists)
  53. {
  54. directoryInfo.Create();
  55. }
  56. }
  57. }
  58. }