manman89

C# Object to String, String to Object

Aug 23rd, 2015
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. Function Convert Object To String
  2.  
  3. public string SERIALIZE_TO_STRING(object DATA)
  4. {
  5. if (DATA == null)
  6. {
  7. return string.Empty;
  8. }
  9. else
  10. {
  11. System.IO.MemoryStream MEMORY_STREAM = new System.IO.MemoryStream();
  12. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BINARY_FORMATTER = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  13. BINARY_FORMATTER.Serialize(MEMORY_STREAM, DATA);
  14. return System.Convert.ToBase64String(MEMORY_STREAM.GetBuffer());
  15. }
  16. }
  17.  
  18. Function Convert String To Object
  19.  
  20. public object DESERIALIZE_FROM_STRING(string BIN_STRING)
  21. {
  22. if (BIN_STRING == null)
  23. {
  24. return null;
  25. }
  26. else
  27. {
  28. if (BIN_STRING.Length == 0)
  29. {
  30. return null;
  31. }
  32. else
  33. {
  34. try
  35. {
  36. byte[] BIN_DATA = System.Convert.FromBase64String(BIN_STRING);
  37. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BINARY_FORMATTER = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  38. System.IO.MemoryStream MEMORY_STREAM = new System.IO.MemoryStream(BIN_DATA);
  39. return BINARY_FORMATTER.Deserialize(MEMORY_STREAM);
  40. }
  41. catch (Exception ex)
  42. {
  43. Console.WriteLine(ex);
  44. return null;
  45. }
  46. }
  47. }
  48. }
  49.  
  50. Test Function
  51.  
  52. private void btn_test_Click(object sender, EventArgs e)
  53. {
  54. string[] array1 = { "", "" };
  55. array1[0] = "a";
  56. array1[1] = "b";
  57.  
  58. MessageBox.Show(array1[0]);
  59. MessageBox.Show(array1[1]);
  60.  
  61. string array1_to_base64 = SERIALIZE_TO_STRING(array1);
  62.  
  63. MessageBox.Show(array1_to_base64);
  64.  
  65. string[] array2 = (string[])DESERIALIZE_FROM_STRING(array1_to_base64);
  66. if (array2 == null)
  67. {
  68. MessageBox.Show("Error");
  69. return;
  70. }
  71. MessageBox.Show(array2[0]);
  72. MessageBox.Show(array2[1]);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment