FileClass.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. using System;
  2. using System.IO;
  3. namespace FileInfoClass
  4. {
  5. public class FileClass
  6. {
  7. //创建文件夹
  8. //参数:path 文件夹路径
  9. public bool CreateFolder(string path)
  10. {
  11. try
  12. {
  13. if (Directory.Exists(path))
  14. {
  15. return true;
  16. }
  17. if (!Directory.Exists(path.Substring(0, path.LastIndexOf("\\"))))
  18. { //若路径中无“\”则表示路径错误
  19. return false;
  20. }
  21. else
  22. {
  23. //创建文件夹
  24. DirectoryInfo dirInfo = Directory.CreateDirectory(path);
  25. return true;
  26. }
  27. }
  28. catch (Exception ex)
  29. {
  30. return false;
  31. }
  32. }
  33. //创建文件
  34. //参数:path 文件路径
  35. public void CreateFile(string path)
  36. {
  37. try
  38. {
  39. if (CreateFolder(path.Substring(0, path.LastIndexOf("\\"))))
  40. {
  41. if (!File.Exists(path))
  42. {
  43. FileStream fs = File.Create(path);
  44. fs.Close();
  45. }
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. return;
  51. }
  52. }
  53. //删除文件
  54. //参数:path 文件夹路径
  55. public void DeleteFile(string path)
  56. {
  57. try
  58. {
  59. if (!File.Exists(path))
  60. {
  61. return;
  62. }
  63. else
  64. {
  65. File.Delete(path);
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. return;
  71. }
  72. }
  73. //写文件
  74. //参数:path 文件夹路径 、content要写的内容
  75. public void WriteFile(string path, string content)
  76. {
  77. try
  78. {
  79. if (!File.Exists(path))
  80. {
  81. CreateFile(path);
  82. }
  83. FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
  84. StreamWriter sw = new StreamWriter(fs);
  85. sw.WriteLine(content);
  86. sw.Close();
  87. }
  88. catch (Exception ex)
  89. {
  90. return;
  91. }
  92. }
  93. /// <summary>
  94. /// 将即时日志保存入日志文件
  95. /// </summary>
  96. public void WriteLogFile(string directoryPath, string content)
  97. {
  98. if (!Directory.Exists(directoryPath))
  99. {
  100. CreateFolder(directoryPath);
  101. }
  102. try
  103. {
  104. //写入新的文件
  105. string filePath = directoryPath + "\\" + DateTime.Now.Date.ToString("yyyyMMdd") + ".log";
  106. FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
  107. StreamWriter sw = new StreamWriter(fs);
  108. sw.WriteLine(content);
  109. sw.Close();
  110. fs.Close();
  111. }
  112. catch (Exception ex)
  113. {
  114. }
  115. }
  116. }
  117. }