LogNetSingle.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. namespace HslCommunication.LogNet
  7. {
  8. /// <summary>
  9. /// 单日志文件对象
  10. /// </summary>
  11. public class LogNetSingle : LogNetBase, ILogNet
  12. {
  13. private string m_fileName = string.Empty;
  14. /// <summary>
  15. /// 实例化一个单文件日志的对象
  16. /// </summary>
  17. /// <param name="filePath"></param>
  18. /// <exception cref="FileNotFoundException"></exception>
  19. public LogNetSingle(string filePath)
  20. {
  21. LogSaveMode = LogNetManagment.LogSaveModeBySingleFile;
  22. m_fileName = filePath;
  23. FileInfo fileInfo = new FileInfo(filePath);
  24. if(!Directory.Exists(fileInfo.DirectoryName))
  25. {
  26. Directory.CreateDirectory(fileInfo.DirectoryName);
  27. }
  28. }
  29. /// <summary>
  30. /// 单日志文件允许清空日志内容
  31. /// </summary>
  32. public void ClearLog()
  33. {
  34. m_fileSaveLock.Enter();
  35. if (!string.IsNullOrEmpty(m_fileName))
  36. {
  37. File.Create(m_fileName).Dispose();
  38. }
  39. m_fileSaveLock.Leave();
  40. }
  41. /// <summary>
  42. /// 获取单日志文件的所有保存记录
  43. /// </summary>
  44. /// <returns></returns>
  45. public string GetAllSavedLog()
  46. {
  47. string result = string.Empty;
  48. m_fileSaveLock.Enter();
  49. if (!string.IsNullOrEmpty(m_fileName))
  50. {
  51. if (File.Exists(m_fileName))
  52. {
  53. StreamReader stream = new StreamReader(m_fileName, Encoding.UTF8);
  54. result = stream.ReadToEnd();
  55. stream.Dispose();
  56. }
  57. }
  58. m_fileSaveLock.Leave();
  59. return result;
  60. }
  61. /// <summary>
  62. /// 获取存储的文件的名称
  63. /// </summary>
  64. /// <returns></returns>
  65. protected override string GetFileSaveName()
  66. {
  67. return m_fileName;
  68. }
  69. /// <summary>
  70. /// 获取所有的日志文件数组,对于单日志文件来说就只有一个
  71. /// </summary>
  72. /// <returns></returns>
  73. public string[] GetExistLogFileNames()
  74. {
  75. return new string[]
  76. {
  77. m_fileName,
  78. };
  79. }
  80. }
  81. }