StreamExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. #if NET5_0_OR_GREATER
  9. using System;
  10. using System.Buffers;
  11. using System.Runtime.InteropServices;
  12. #endif
  13. namespace Masuit.Tools
  14. {
  15. public static class StreamExtensions
  16. {
  17. /// <summary>
  18. /// 将流转换为内存流
  19. /// </summary>
  20. /// <param name="stream"></param>
  21. /// <returns></returns>
  22. public static MemoryStream SaveAsMemoryStream(this Stream stream)
  23. {
  24. stream.Position = 0;
  25. return new MemoryStream(stream.ToArray());
  26. }
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="stream"></param>
  31. /// <returns></returns>
  32. public static byte[] ToArray(this Stream stream)
  33. {
  34. stream.Position = 0;
  35. byte[] bytes = new byte[stream.Length];
  36. stream.Read(bytes, 0, bytes.Length);
  37. // 设置当前流的位置为流的开始
  38. stream.Seek(0, SeekOrigin.Begin);
  39. return bytes;
  40. }
  41. /// <summary>
  42. /// 流洗码,在流的末端随即增加几个空字节,重要数据请谨慎使用,可能造成流损坏
  43. /// </summary>
  44. /// <param name="stream"></param>
  45. public static void ShuffleCode(this Stream stream)
  46. {
  47. if (stream.CanWrite && stream.CanSeek)
  48. {
  49. var position = stream.Position;
  50. stream.Position = stream.Length;
  51. for (int i = 0; i < new Random().Next(1, 20); i++)
  52. {
  53. stream.WriteByte(0);
  54. }
  55. stream.Flush();
  56. stream.Position = position;
  57. }
  58. }
  59. /// <summary>
  60. /// 读取所有行
  61. /// </summary>
  62. /// <param name="stream"></param>
  63. /// <param name="closeAfter">读取完毕后关闭流</param>
  64. /// <returns></returns>
  65. public static List<string> ReadAllLines(this StreamReader stream, bool closeAfter = true)
  66. {
  67. var stringList = new List<string>();
  68. string str;
  69. while ((str = stream.ReadLine()) != null)
  70. {
  71. stringList.Add(str);
  72. }
  73. if (closeAfter)
  74. {
  75. stream.Close();
  76. stream.Dispose();
  77. }
  78. return stringList;
  79. }
  80. /// <summary>
  81. /// 读取所有行
  82. /// </summary>
  83. /// <param name="stream"></param>
  84. /// <param name="encoding"></param>
  85. /// <param name="closeAfter">读取完毕后关闭流</param>
  86. /// <returns></returns>
  87. public static List<string> ReadAllLines(this FileStream stream, Encoding encoding, bool closeAfter = true)
  88. {
  89. var stringList = new List<string>();
  90. string str;
  91. var sr = new StreamReader(stream, encoding);
  92. while ((str = sr.ReadLine()) != null)
  93. {
  94. stringList.Add(str);
  95. }
  96. if (closeAfter)
  97. {
  98. sr.Close();
  99. sr.Dispose();
  100. stream.Close();
  101. stream.Dispose();
  102. }
  103. return stringList;
  104. }
  105. /// <summary>
  106. /// 读取所有文本
  107. /// </summary>
  108. /// <param name="stream"></param>
  109. /// <param name="encoding"></param>
  110. /// <param name="closeAfter">读取完毕后关闭流</param>
  111. /// <returns></returns>
  112. public static string ReadAllText(this FileStream stream, Encoding encoding, bool closeAfter = true)
  113. {
  114. var sr = new StreamReader(stream, encoding);
  115. var text = sr.ReadToEnd();
  116. if (closeAfter)
  117. {
  118. sr.Close();
  119. sr.Dispose();
  120. stream.Close();
  121. stream.Dispose();
  122. }
  123. return text;
  124. }
  125. /// <summary>
  126. /// 写入所有文本
  127. /// </summary>
  128. /// <param name="stream"></param>
  129. /// <param name="content"></param>
  130. /// <param name="encoding"></param>
  131. /// <param name="closeAfter">读取完毕后关闭流</param>
  132. /// <returns></returns>
  133. public static void WriteAllText(this FileStream stream, string content, Encoding encoding, bool closeAfter = true)
  134. {
  135. var sw = new StreamWriter(stream, encoding);
  136. stream.SetLength(0);
  137. sw.Write(content);
  138. if (closeAfter)
  139. {
  140. sw.Close();
  141. sw.Dispose();
  142. stream.Close();
  143. stream.Dispose();
  144. }
  145. }
  146. /// <summary>
  147. /// 写入所有文本行
  148. /// </summary>
  149. /// <param name="stream"></param>
  150. /// <param name="lines"></param>
  151. /// <param name="encoding"></param>
  152. /// <param name="closeAfter">读取完毕后关闭流</param>
  153. /// <returns></returns>
  154. public static void WriteAllLines(this FileStream stream, IEnumerable<string> lines, Encoding encoding, bool closeAfter = true)
  155. {
  156. var sw = new StreamWriter(stream, encoding);
  157. stream.SetLength(0);
  158. foreach (var line in lines)
  159. {
  160. sw.WriteLine(line);
  161. }
  162. sw.Flush();
  163. if (closeAfter)
  164. {
  165. sw.Close();
  166. sw.Dispose();
  167. stream.Close();
  168. stream.Dispose();
  169. }
  170. }
  171. /// <summary>
  172. /// 共享读写打开文件
  173. /// </summary>
  174. /// <param name="file"></param>
  175. /// <returns></returns>
  176. public static FileStream ShareReadWrite(this FileInfo file)
  177. {
  178. return file.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
  179. }
  180. /// <summary>
  181. /// 读取所有行
  182. /// </summary>
  183. /// <param name="stream"></param>
  184. /// <param name="closeAfter">读取完毕后关闭流</param>
  185. /// <returns></returns>
  186. public static async Task<List<string>> ReadAllLinesAsync(this StreamReader stream, bool closeAfter = true)
  187. {
  188. var stringList = new List<string>();
  189. string str;
  190. while ((str = await stream.ReadLineAsync().ConfigureAwait(false)) != null)
  191. {
  192. stringList.Add(str);
  193. }
  194. if (closeAfter)
  195. {
  196. stream.Close();
  197. stream.Dispose();
  198. }
  199. return stringList;
  200. }
  201. /// <summary>
  202. /// 读取所有行
  203. /// </summary>
  204. /// <param name="stream"></param>
  205. /// <param name="encoding"></param>
  206. /// <param name="closeAfter">读取完毕后关闭流</param>
  207. /// <returns></returns>
  208. public static async Task<List<string>> ReadAllLinesAsync(this FileStream stream, Encoding encoding, bool closeAfter = true)
  209. {
  210. var stringList = new List<string>();
  211. string str;
  212. var sr = new StreamReader(stream, encoding);
  213. while ((str = await sr.ReadLineAsync().ConfigureAwait(false)) != null)
  214. {
  215. stringList.Add(str);
  216. }
  217. if (closeAfter)
  218. {
  219. sr.Close();
  220. sr.Dispose();
  221. stream.Close();
  222. #if NET5_0_OR_GREATER
  223. await stream.DisposeAsync().ConfigureAwait(false);
  224. #else
  225. stream.Dispose();
  226. #endif
  227. }
  228. return stringList;
  229. }
  230. /// <summary>
  231. /// 读取所有文本
  232. /// </summary>
  233. /// <param name="stream"></param>
  234. /// <param name="encoding"></param>
  235. /// <param name="closeAfter">读取完毕后关闭流</param>
  236. /// <returns></returns>
  237. public static async Task<string> ReadAllTextAsync(this FileStream stream, Encoding encoding, bool closeAfter = true)
  238. {
  239. var sr = new StreamReader(stream, encoding);
  240. var text = await sr.ReadToEndAsync().ConfigureAwait(false);
  241. if (closeAfter)
  242. {
  243. sr.Close();
  244. sr.Dispose();
  245. stream.Close();
  246. #if NET5_0_OR_GREATER
  247. await stream.DisposeAsync().ConfigureAwait(false);
  248. #else
  249. stream.Dispose();
  250. #endif
  251. }
  252. return text;
  253. }
  254. /// <summary>
  255. /// 写入所有文本
  256. /// </summary>
  257. /// <param name="stream"></param>
  258. /// <param name="content"></param>
  259. /// <param name="encoding"></param>
  260. /// <param name="closeAfter">读取完毕后关闭流</param>
  261. /// <returns></returns>
  262. public static async Task WriteAllTextAsync(this FileStream stream, string content, Encoding encoding, bool closeAfter = true)
  263. {
  264. var sw = new StreamWriter(stream, encoding);
  265. stream.SetLength(0);
  266. await sw.WriteAsync(content).ConfigureAwait(false);
  267. await sw.FlushAsync().ConfigureAwait(false);
  268. if (closeAfter)
  269. {
  270. sw.Close();
  271. stream.Close();
  272. #if NET5_0_OR_GREATER
  273. await sw.DisposeAsync().ConfigureAwait(false);
  274. await stream.DisposeAsync().ConfigureAwait(false);
  275. #else
  276. sw.Dispose();
  277. stream.Dispose();
  278. #endif
  279. }
  280. }
  281. /// <summary>
  282. /// 写入所有文本行
  283. /// </summary>
  284. /// <param name="stream"></param>
  285. /// <param name="lines"></param>
  286. /// <param name="encoding"></param>
  287. /// <param name="closeAfter">读取完毕后关闭流</param>
  288. /// <returns></returns>
  289. public static async Task WriteAllLinesAsync(this FileStream stream, IEnumerable<string> lines, Encoding encoding, bool closeAfter = true)
  290. {
  291. var sw = new StreamWriter(stream, encoding);
  292. stream.SetLength(0);
  293. foreach (var line in lines)
  294. {
  295. await sw.WriteLineAsync(line).ConfigureAwait(false);
  296. }
  297. await sw.FlushAsync().ConfigureAwait(false);
  298. if (closeAfter)
  299. {
  300. sw.Close();
  301. stream.Close();
  302. #if NET5_0_OR_GREATER
  303. await sw.DisposeAsync().ConfigureAwait(false);
  304. await stream.DisposeAsync().ConfigureAwait(false);
  305. #else
  306. sw.Dispose();
  307. stream.Dispose();
  308. #endif
  309. }
  310. }
  311. #if NET5_0_OR_GREATER
  312. /// <summary>
  313. ///
  314. /// </summary>
  315. /// <param name="stream"></param>
  316. /// <param name="cancellationToken"></param>
  317. /// <returns></returns>
  318. public static async Task<byte[]> ToArrayAsync(this Stream stream, CancellationToken cancellationToken = default)
  319. {
  320. stream.Position = 0;
  321. byte[] bytes = new byte[stream.Length];
  322. await stream.ReadAsync(bytes, cancellationToken);
  323. stream.Seek(0, SeekOrigin.Begin);
  324. return bytes;
  325. }
  326. #endif
  327. }
  328. }