StreamHelpers.CopyValidation.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Buffers;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.IO
  8. {
  9. /// <summary>Provides methods to help in the implementation of Stream-derived types.</summary>
  10. internal static partial class StreamHelpers
  11. {
  12. /// <summary>Validate the arguments to CopyTo, as would Stream.CopyTo.</summary>
  13. public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
  14. {
  15. if (destination == null)
  16. {
  17. throw new ArgumentNullException(nameof(destination));
  18. }
  19. if (bufferSize <= 0)
  20. {
  21. throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum);
  22. }
  23. bool sourceCanRead = source.CanRead;
  24. if (!sourceCanRead && !source.CanWrite)
  25. {
  26. throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
  27. }
  28. bool destinationCanWrite = destination.CanWrite;
  29. if (!destinationCanWrite && !destination.CanRead)
  30. {
  31. throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
  32. }
  33. if (!sourceCanRead)
  34. {
  35. throw new NotSupportedException(SR.NotSupported_UnreadableStream);
  36. }
  37. if (!destinationCanWrite)
  38. {
  39. throw new NotSupportedException(SR.NotSupported_UnwritableStream);
  40. }
  41. }
  42. public static void ValidateCopyToArgs(Stream source, Delegate callback, int bufferSize)
  43. {
  44. if (callback == null)
  45. {
  46. throw new ArgumentNullException(nameof(callback));
  47. }
  48. if (bufferSize <= 0)
  49. {
  50. throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum);
  51. }
  52. if (!source.CanRead)
  53. {
  54. throw source.CanWrite ? (Exception)
  55. new NotSupportedException(SR.NotSupported_UnreadableStream) :
  56. new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
  57. }
  58. }
  59. }
  60. }