StreamExtensions.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 SixLabors.ImageSharp;
  10. using SixLabors.ImageSharp.PixelFormats;
  11. using System;
  12. using System.Buffers;
  13. using System.Runtime.InteropServices;
  14. #endif
  15. namespace Masuit.Tools;
  16. public static class StreamExtensions
  17. {
  18. /// <summary>
  19. /// 将流转换为内存流
  20. /// </summary>
  21. /// <param name="stream"></param>
  22. /// <returns></returns>
  23. public static PooledMemoryStream SaveAsMemoryStream(this Stream stream)
  24. {
  25. if (stream is PooledMemoryStream pooledMemoryStream)
  26. {
  27. return pooledMemoryStream;
  28. }
  29. stream.Position = 0;
  30. var ms = new PooledMemoryStream();
  31. stream.CopyTo(ms);
  32. stream.Position = 0;
  33. return ms;
  34. }
  35. /// <summary>
  36. ///
  37. /// </summary>
  38. /// <param name="stream"></param>
  39. /// <returns></returns>
  40. public static byte[] ToArray(this Stream stream)
  41. {
  42. stream.Position = 0;
  43. byte[] bytes = new byte[stream.Length];
  44. _ = stream.Read(bytes, 0, bytes.Length);
  45. // 设置当前流的位置为流的开始
  46. stream.Seek(0, SeekOrigin.Begin);
  47. return bytes;
  48. }
  49. /// <summary>
  50. /// 流洗码,在流的末端随即增加几个空字节,重要数据请谨慎使用,可能造成流损坏
  51. /// </summary>
  52. /// <param name="stream"></param>
  53. public static void ShuffleCode(this Stream stream)
  54. {
  55. if (stream.CanWrite && stream.CanSeek)
  56. {
  57. var position = stream.Position;
  58. stream.Position = stream.Length;
  59. for (int i = 0; i < new Random().Next(1, 20); i++)
  60. {
  61. stream.WriteByte(0);
  62. }
  63. stream.Flush();
  64. stream.Position = position;
  65. }
  66. }
  67. /// <summary>
  68. /// 读取所有行
  69. /// </summary>
  70. /// <param name="stream"></param>
  71. /// <param name="closeAfter">读取完毕后关闭流</param>
  72. /// <returns></returns>
  73. public static List<string> ReadAllLines(this StreamReader stream, bool closeAfter = true)
  74. {
  75. var stringList = new List<string>();
  76. while (stream.ReadLine() is { } str)
  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. var sr = new StreamReader(stream, encoding);
  98. while (sr.ReadLine() is { } str)
  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. while (await stream.ReadLineAsync().ConfigureAwait(false) is { } str)
  196. {
  197. stringList.Add(str);
  198. }
  199. if (closeAfter)
  200. {
  201. stream.Close();
  202. stream.Dispose();
  203. }
  204. return stringList;
  205. }
  206. /// <summary>
  207. /// 读取所有行
  208. /// </summary>
  209. /// <param name="stream"></param>
  210. /// <param name="encoding"></param>
  211. /// <param name="closeAfter">读取完毕后关闭流</param>
  212. /// <returns></returns>
  213. public static async Task<List<string>> ReadAllLinesAsync(this FileStream stream, Encoding encoding, bool closeAfter = true)
  214. {
  215. var stringList = new List<string>();
  216. var sr = new StreamReader(stream, encoding);
  217. while (await sr.ReadLineAsync().ConfigureAwait(false) is { } str)
  218. {
  219. stringList.Add(str);
  220. }
  221. if (closeAfter)
  222. {
  223. sr.Close();
  224. sr.Dispose();
  225. stream.Close();
  226. #if NET5_0_OR_GREATER
  227. await stream.DisposeAsync().ConfigureAwait(false);
  228. #else
  229. stream.Dispose();
  230. #endif
  231. }
  232. return stringList;
  233. }
  234. /// <summary>
  235. /// 读取所有文本
  236. /// </summary>
  237. /// <param name="stream"></param>
  238. /// <param name="encoding"></param>
  239. /// <param name="closeAfter">读取完毕后关闭流</param>
  240. /// <returns></returns>
  241. public static async Task<string> ReadAllTextAsync(this FileStream stream, Encoding encoding, bool closeAfter = true)
  242. {
  243. var sr = new StreamReader(stream, encoding);
  244. var text = await sr.ReadToEndAsync().ConfigureAwait(false);
  245. if (closeAfter)
  246. {
  247. sr.Close();
  248. sr.Dispose();
  249. stream.Close();
  250. #if NET5_0_OR_GREATER
  251. await stream.DisposeAsync().ConfigureAwait(false);
  252. #else
  253. stream.Dispose();
  254. #endif
  255. }
  256. return text;
  257. }
  258. /// <summary>
  259. /// 写入所有文本
  260. /// </summary>
  261. /// <param name="stream"></param>
  262. /// <param name="content"></param>
  263. /// <param name="encoding"></param>
  264. /// <param name="closeAfter">读取完毕后关闭流</param>
  265. /// <returns></returns>
  266. public static async Task WriteAllTextAsync(this FileStream stream, string content, Encoding encoding, bool closeAfter = true)
  267. {
  268. var sw = new StreamWriter(stream, encoding);
  269. stream.SetLength(0);
  270. await sw.WriteAsync(content).ConfigureAwait(false);
  271. await sw.FlushAsync().ConfigureAwait(false);
  272. if (closeAfter)
  273. {
  274. sw.Close();
  275. stream.Close();
  276. #if NET5_0_OR_GREATER
  277. await sw.DisposeAsync().ConfigureAwait(false);
  278. await stream.DisposeAsync().ConfigureAwait(false);
  279. #else
  280. sw.Dispose();
  281. stream.Dispose();
  282. #endif
  283. }
  284. }
  285. /// <summary>
  286. /// 写入所有文本行
  287. /// </summary>
  288. /// <param name="stream"></param>
  289. /// <param name="lines"></param>
  290. /// <param name="encoding"></param>
  291. /// <param name="closeAfter">读取完毕后关闭流</param>
  292. /// <returns></returns>
  293. public static async Task WriteAllLinesAsync(this FileStream stream, IEnumerable<string> lines, Encoding encoding, bool closeAfter = true)
  294. {
  295. var sw = new StreamWriter(stream, encoding);
  296. stream.SetLength(0);
  297. foreach (var line in lines)
  298. {
  299. await sw.WriteLineAsync(line).ConfigureAwait(false);
  300. }
  301. await sw.FlushAsync().ConfigureAwait(false);
  302. if (closeAfter)
  303. {
  304. sw.Close();
  305. stream.Close();
  306. #if NET5_0_OR_GREATER
  307. await sw.DisposeAsync().ConfigureAwait(false);
  308. await stream.DisposeAsync().ConfigureAwait(false);
  309. #else
  310. sw.Dispose();
  311. stream.Dispose();
  312. #endif
  313. }
  314. }
  315. #if NET5_0_OR_GREATER
  316. /// <summary>
  317. ///
  318. /// </summary>
  319. /// <param name="stream"></param>
  320. /// <param name="cancellationToken"></param>
  321. /// <returns></returns>
  322. public static async Task<byte[]> ToArrayAsync(this Stream stream, CancellationToken cancellationToken = default)
  323. {
  324. stream.Position = 0;
  325. byte[] bytes = new byte[stream.Length];
  326. await stream.ReadAsync(bytes, cancellationToken);
  327. stream.Seek(0, SeekOrigin.Begin);
  328. return bytes;
  329. }
  330. public static Image<Rgba32> AsImage(this Stream stream)
  331. {
  332. return Image.Load<Rgba32>(stream);
  333. }
  334. #endif
  335. }