StreamExtensions.cs 2.4 KB

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