StreamExtensions.cs 11 KB

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