Working with byte arrays


/ Published in: C#
Save to your folder(s)

Some static methods to help in working with byte arrays


Copy this code and paste it in your HTML
  1. namespace Kyrathasoft.ArraysAndCollections.WorkingWithByteArrays {
  2.  
  3. using System;
  4. using System.IO;
  5. using System.Diagnostics;
  6.  
  7. public static class clsWorkWithByteArrays {
  8.  
  9. public static byte[] ReadByteArrayFromFile(string fileName) {
  10. byte[] buff = null;
  11. FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  12. BinaryReader br = new BinaryReader(fs);
  13. long numBytes = new FileInfo(fileName).Length;
  14. buff = br.ReadBytes((int)numBytes);
  15. return buff;
  16. }
  17.  
  18. public static byte[] StringToByteArray(string str) {
  19. System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
  20. return encoding.GetBytes(str);
  21. }
  22.  
  23. public static bool WroteByteArrayToFileSuccessfully(byte[] buff, string fileName) {
  24. bool response = false;
  25.  
  26. try {
  27. FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
  28. BinaryWriter bw = new BinaryWriter(fs);
  29. bw.Write(buff);
  30. bw.Close();
  31. response = true;
  32. }
  33. catch (Exception ex) {
  34. Debug.WriteLine("");
  35. Debug.WriteLine("Error in WroteByteArrayToFileSuccessfully()");
  36. Debug.WriteLine(ex.Message);
  37. Debug.WriteLine("");
  38. }
  39.  
  40. return response;
  41. }
  42. }
  43. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.