TxtTool.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Y.Utils.BaseUtils;
  6. using Y.Utils.FileUtils;
  7. namespace Y.Utils.TxtUtils
  8. {
  9. public class TxtTool
  10. {
  11. public static bool Append(string file, List<string> txt)
  12. {
  13. try
  14. {
  15. DirTool.Create(Path.GetDirectoryName(file));
  16. using (StreamWriter sw = new StreamWriter(file, true))
  17. {
  18. if (!ListTool.IsNullOrEmpty(txt))
  19. foreach (var t in txt)
  20. sw.WriteLine(t);
  21. }
  22. return true;
  23. }
  24. catch (Exception e) { }
  25. return false;
  26. }
  27. public static bool Append(string file, string txt)
  28. {
  29. try
  30. {
  31. DirTool.Create(Path.GetDirectoryName(file));
  32. using (StreamWriter sw = new StreamWriter(file, true))
  33. {
  34. sw.WriteLine(txt);
  35. }
  36. return true;
  37. }
  38. catch (Exception e) { }
  39. return false;
  40. }
  41. public static bool Create(string file, string txt)
  42. {
  43. try
  44. {
  45. DirTool.Create(Path.GetDirectoryName(file));
  46. using (StreamWriter sw = new StreamWriter(file, false, Encoding.UTF8))
  47. {
  48. sw.WriteLine(txt);
  49. }
  50. return true;
  51. }
  52. catch (Exception e) { }
  53. return false;
  54. }
  55. public static string Read(string file)
  56. {
  57. try
  58. {
  59. using (StreamReader sr = new StreamReader(file, Encoding.UTF8))
  60. {
  61. string result = "", line;
  62. while ((line = sr.ReadLine()) != null)
  63. result += line.ToString();
  64. return result;
  65. }
  66. }
  67. catch (Exception e) { }
  68. return null;
  69. }
  70. public static List<string> ReadLine(string file)
  71. {
  72. try
  73. {
  74. using (StreamReader sr = new StreamReader(file, Encoding.UTF8))
  75. {
  76. List<string> result = new List<string>();
  77. string line;
  78. while ((line = sr.ReadLine()) != null)
  79. result.Add(line.ToString());
  80. return result;
  81. }
  82. }
  83. catch (Exception e) { }
  84. return null;
  85. }
  86. public static long CountLine(string file, string[] filter)
  87. {
  88. long count = 0;
  89. try
  90. {
  91. using (StreamReader sr = new StreamReader(file, Encoding.UTF8))
  92. {
  93. string line;
  94. while ((line = sr.ReadLine()) != null)
  95. {
  96. bool access = true;
  97. if (!ListTool.IsNullOrEmpty(filter))
  98. {
  99. foreach (var f in filter)
  100. {
  101. if (line.Trim() == f) access = false;
  102. }
  103. }
  104. if (access) count++;
  105. }
  106. }
  107. }
  108. catch (Exception e) { }
  109. return count;
  110. }
  111. }
  112. }