StreamExtensions.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. namespace MediaBrowser.Common.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. {
  29. return ReadAllLines(reader).ToArray();
  30. }
  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()) != 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. /// <returns>All lines in the stream.</returns>
  50. public static async IAsyncEnumerable<string> ReadAllLinesAsync(this TextReader reader)
  51. {
  52. string? line;
  53. while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
  54. {
  55. yield return line;
  56. }
  57. }
  58. }
  59. }