StreamExtensions.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace S7.Net
  6. {
  7. /// <summary>
  8. /// Extensions for Streams
  9. /// </summary>
  10. public static class StreamExtensions
  11. {
  12. /// <summary>
  13. /// Reads bytes from the stream into the buffer until exactly the requested number of bytes (or EOF) have been read
  14. /// </summary>
  15. /// <param name="stream">the Stream to read from</param>
  16. /// <param name="buffer">the buffer to read into</param>
  17. /// <param name="offset">the offset in the buffer to read into</param>
  18. /// <param name="count">the amount of bytes to read into the buffer</param>
  19. /// <returns>returns the amount of read bytes</returns>
  20. public static int ReadExact(this Stream stream, byte[] buffer, int offset, int count)
  21. {
  22. int read = 0;
  23. int received;
  24. do
  25. {
  26. received = stream.Read(buffer, offset + read, count - read);
  27. read += received;
  28. }
  29. while (read < count && received > 0);
  30. return read;
  31. }
  32. /// <summary>
  33. /// Reads bytes from the stream into the buffer until exactly the requested number of bytes (or EOF) have been read
  34. /// </summary>
  35. /// <param name="stream">the Stream to read from</param>
  36. /// <param name="buffer">the buffer to read into</param>
  37. /// <param name="offset">the offset in the buffer to read into</param>
  38. /// <param name="count">the amount of bytes to read into the buffer</param>
  39. /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
  40. /// <returns>returns the amount of read bytes</returns>
  41. public static async Task<int> ReadExactAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  42. {
  43. int read = 0;
  44. int received;
  45. do
  46. {
  47. received = await stream.ReadAsync(buffer, offset + read, count - read, cancellationToken).ConfigureAwait(false);
  48. read += received;
  49. }
  50. while (read < count && received > 0);
  51. return read;
  52. }
  53. }
  54. }