Function Convert Object To String
public string SERIALIZE_TO_STRING(object DATA)
{
if (DATA == null)
{
return string.Empty;
}
else
{
System.IO.MemoryStream MEMORY_STREAM = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BINARY_FORMATTER = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
BINARY_FORMATTER.Serialize(MEMORY_STREAM, DATA);
return System.Convert.ToBase64String(MEMORY_STREAM.GetBuffer());
}
}
Function Convert String To Object
public object DESERIALIZE_FROM_STRING(string BIN_STRING)
{
if (BIN_STRING == null)
{
return null;
}
else
{
if (BIN_STRING.Length == 0)
{
return null;
}
else
{
try
{
byte[] BIN_DATA = System.Convert.FromBase64String(BIN_STRING);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BINARY_FORMATTER = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream MEMORY_STREAM = new System.IO.MemoryStream(BIN_DATA);
return BINARY_FORMATTER.Deserialize(MEMORY_STREAM);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
}
}
Test Function
private void btn_test_Click(object sender, EventArgs e)
{
string[] array1 = { "", "" };
array1[0] = "a";
array1[1] = "b";
MessageBox.Show(array1[0]);
MessageBox.Show(array1[1]);
string array1_to_base64 = SERIALIZE_TO_STRING(array1);
MessageBox.Show(array1_to_base64);
string[] array2 = (string[])DESERIALIZE_FROM_STRING(array1_to_base64);
if (array2 == null)
{
MessageBox.Show("Error");
return;
}
MessageBox.Show(array2[0]);
MessageBox.Show(array2[1]);
}
Nguồn: Sharecode.vn