FileHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace Admin.Core.Common.Helpers
  5. {
  6. public class FileHelper : IDisposable
  7. {
  8. private bool _alreadyDispose = false;
  9. public FileHelper()
  10. {
  11. }
  12. ~FileHelper()
  13. {
  14. Dispose();
  15. }
  16. protected virtual void Dispose(bool isDisposing)
  17. {
  18. if (_alreadyDispose) return;
  19. _alreadyDispose = true;
  20. }
  21. public void Dispose()
  22. {
  23. Dispose(true);
  24. GC.SuppressFinalize(this);
  25. }
  26. #region 写文件
  27. /// <summary>
  28. /// 写文件
  29. /// </summary>
  30. /// <param name="Path">文件路径</param>
  31. /// <param name="Strings">文件内容</param>
  32. public static void WriteFile(string Path, string Strings)
  33. {
  34. if (!File.Exists(Path))
  35. {
  36. File.Create(Path).Close();
  37. }
  38. StreamWriter streamWriter = new StreamWriter(Path, false);
  39. streamWriter.Write(Strings);
  40. streamWriter.Close();
  41. streamWriter.Dispose();
  42. }
  43. /// <summary>
  44. /// 写文件
  45. /// </summary>
  46. /// <param name="Path">文件路径</param>
  47. /// <param name="Strings">文件内容</param>
  48. /// <param name="encode">编码格式</param>
  49. public static void WriteFile(string Path, string Strings, Encoding encode)
  50. {
  51. if (!File.Exists(Path))
  52. {
  53. File.Create(Path).Close();
  54. }
  55. StreamWriter streamWriter = new StreamWriter(Path, false, encode);
  56. streamWriter.Write(Strings);
  57. streamWriter.Close();
  58. streamWriter.Dispose();
  59. }
  60. #endregion 写文件
  61. #region 读文件
  62. /// <summary>
  63. /// 读文件
  64. /// </summary>
  65. /// <param name="Path">文件路径</param>
  66. /// <returns></returns>
  67. public static string ReadFile(string Path)
  68. {
  69. string s;
  70. if (!File.Exists(Path))
  71. s = "不存在相应的目录";
  72. else
  73. {
  74. StreamReader streamReader = new StreamReader(Path);
  75. s = streamReader.ReadToEnd();
  76. streamReader.Close();
  77. streamReader.Dispose();
  78. }
  79. return s;
  80. }
  81. /// <summary>
  82. /// 读文件
  83. /// </summary>
  84. /// <param name="Path">文件路径</param>
  85. /// <param name="encode">编码格式</param>
  86. /// <returns></returns>
  87. public static string ReadFile(string Path, Encoding encode)
  88. {
  89. string s;
  90. if (!File.Exists(Path))
  91. s = "不存在相应的目录";
  92. else
  93. {
  94. StreamReader streamReader = new StreamReader(Path, encode);
  95. s = streamReader.ReadToEnd();
  96. streamReader.Close();
  97. streamReader.Dispose();
  98. }
  99. return s;
  100. }
  101. #endregion 读文件
  102. }
  103. }