StreamExtensions.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Jellyfin.Extensions
  6. {
  7. /// <summary>
  8. /// Class BaseExtensions.
  9. /// </summary>
  10. public static class StreamExtensions
  11. {
  12. /// <summary>
  13. /// Reads all lines in the <see cref="Stream" />.
  14. /// </summary>
  15. /// <param name="stream">The <see cref="Stream" /> to read from.</param>
  16. /// <returns>All lines in the stream.</returns>
  17. public static string[] ReadAllLines(this Stream stream)
  18. => ReadAllLines(stream, Encoding.UTF8);
  19. /// <summary>
  20. /// Reads all lines in the <see cref="Stream" />.
  21. /// </summary>
  22. /// <param name="stream">The <see cref="Stream" /> to read from.</param>
  23. /// <param name="encoding">The character encoding to use.</param>
  24. /// <returns>All lines in the stream.</returns>
  25. public static string[] ReadAllLines(this Stream stream, Encoding encoding)
  26. {
  27. using StreamReader reader = new StreamReader(stream, encoding);
  28. return ReadAllLines(reader).ToArray();
  29. }
  30. /// <summary>
  31. /// Reads all lines in the <see cref="TextReader" />.
  32. /// </summary>
  33. /// <param name="reader">The <see cref="TextReader" /> to read from.</param>
  34. /// <returns>All lines in the stream.</returns>
  35. public static IEnumerable<string> ReadAllLines(this TextReader reader)
  36. {
  37. string? line;
  38. while ((line = reader.ReadLine()) is not null)
  39. {
  40. yield return line;
  41. }
  42. }
  43. /// <summary>
  44. /// Reads all lines in the <see cref="TextReader" />.
  45. /// </summary>
  46. /// <param name="reader">The <see cref="TextReader" /> to read from.</param>
  47. /// <returns>All lines in the stream.</returns>
  48. public static async IAsyncEnumerable<string> ReadAllLinesAsync(this TextReader reader)
  49. {
  50. string? line;
  51. while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) is not null)
  52. {
  53. yield return line;
  54. }
  55. }
  56. }
  57. }