StreamExtensions.cs 11 KB

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