code_junkie

Creating a byte array from a stream

Nov 11th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. Stream s;
  2. byte[] b;
  3.  
  4. using (BinaryReader br = new BinaryReader(s))
  5. {
  6. b = br.ReadBytes(s.Length);
  7. }
  8.  
  9. public static byte[] ReadFully(Stream input)
  10. {
  11. byte[] buffer = new byte[16*1024];
  12. using (MemoryStream ms = new MemoryStream())
  13. {
  14. int read;
  15. while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
  16. {
  17. ms.Write(buffer, 0, read);
  18. }
  19. return ms.ToArray();
  20. }
  21. }
  22.  
  23. public static byte[] ReadFully(Stream input)
  24. {
  25. using (MemoryStream ms = new MemoryStream())
  26. {
  27. input.CopyTo(ms);
  28. return ms.ToArray();
  29. }
  30. }
  31.  
  32. public static byte[] StreamToByteArray(Stream stream)
  33. {
  34. if (stream is MemoryStream)
  35. {
  36. return ((MemoryStream)stream).ToArray();
  37. }
  38. else
  39. {
  40. // Jon Skeet's accepted answer
  41. return ReadFully(stream);
  42. }
  43. }
  44.  
  45. MemoryStream ms = new MemoryStream();
  46. file.PostedFile.InputStream.CopyTo(ms);
  47. var byts = ms.ToArray();
  48. ms.Dispose();
  49.  
  50. Stream s;
  51. byte[] b;
  52.  
  53. if (s.Length > int.MaxValue) {
  54. throw new Exception("This stream is larger than the conversion algorithm can currently handle.");
  55. }
  56.  
  57. using (var br = new BinaryReader(s)) {
  58. b = br.ReadBytes((int)s.Length);
  59. }
Add Comment
Please, Sign In to add comment