IoExtension.cs 926 B

12345678910111213141516171819202122232425262728293031323334
  1. using System.Text;
  2. namespace Bmp.Core.Common.Utility;
  3. public static class IoExtension
  4. {
  5. public static IEnumerable<string> ReadLines(this Stream stream, Encoding? encoding = null)
  6. {
  7. using var reader = encoding == null
  8. ? new StreamReader(stream, leaveOpen: true)
  9. : new StreamReader(stream, encoding, true);
  10. while (true)
  11. {
  12. var line = reader.ReadLine();
  13. if (line == null) yield break;
  14. yield return line;
  15. }
  16. }
  17. public static byte[] ReadBytes(this Stream stream, int count)
  18. {
  19. var buffer = new byte[count];
  20. var bytesRead = 0;
  21. while (bytesRead < buffer.Length)
  22. {
  23. var bytesToRead = buffer.Length - bytesRead;
  24. var n = stream.Read(buffer, bytesRead, bytesToRead);
  25. if (n == 0) break;
  26. bytesRead += n;
  27. }
  28. return buffer;
  29. }
  30. }