ByteUtils.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace Utilities
  6. {
  7. public class ByteUtils
  8. {
  9. public static byte[] Concatenate(byte[] a, byte[] b)
  10. {
  11. byte[] result = new byte[a.Length + b.Length];
  12. Array.Copy(a, 0, result, 0, a.Length);
  13. Array.Copy(b, 0, result, a.Length, b.Length);
  14. return result;
  15. }
  16. public static bool AreByteArraysEqual(byte[] array1, byte[] array2)
  17. {
  18. if (array1.Length != array2.Length)
  19. {
  20. return false;
  21. }
  22. for (int index = 0; index < array1.Length; index++)
  23. {
  24. if (array1[index] != array2[index])
  25. {
  26. return false;
  27. }
  28. }
  29. return true;
  30. }
  31. public static long CopyStream(Stream input, Stream output)
  32. {
  33. // input may not support seeking, so don't use input.Position
  34. return CopyStream(input, output, Int64.MaxValue);
  35. }
  36. public static long CopyStream(Stream input, Stream output, long count)
  37. {
  38. const int MaxBufferSize = 4194304; // 4 MB
  39. int bufferSize = (int)Math.Min(MaxBufferSize, count);
  40. byte[] buffer = new byte[bufferSize];
  41. long totalBytesRead = 0;
  42. while (totalBytesRead < count)
  43. {
  44. int numberOfBytesToRead = (int)Math.Min(bufferSize, count - totalBytesRead);
  45. int bytesRead = input.Read(buffer, 0, numberOfBytesToRead);
  46. totalBytesRead += bytesRead;
  47. output.Write(buffer, 0, bytesRead);
  48. if (bytesRead < numberOfBytesToRead) // no more bytes to read from input stream
  49. {
  50. return totalBytesRead;
  51. }
  52. }
  53. return totalBytesRead;
  54. }
  55. }
  56. }