Created
May 25, 2019 00:18
-
-
Save hasokeric/eef8eeeb1320512eb7a13161b4cf1993 to your computer and use it in GitHub Desktop.
StringToObject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Base64 Encode | |
* | |
* @var string | |
* @type Custom Function | |
* @subtype Helper | |
* @return string | |
*/ | |
public static string Base64Encode(string plainText) | |
{ | |
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); | |
return System.Convert.ToBase64String(plainTextBytes); | |
} | |
/** | |
* Base64 Decode | |
* | |
* @var string Base64 Encoded | |
* @type Custom Function | |
* @subtype Helper | |
* @return string | |
*/ | |
public static string Base64Decode(string base64EncodedData) | |
{ | |
byte[] base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); | |
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); | |
} | |
/** | |
* Serialize a Object into a Base64 String for Storage | |
* | |
* @var object | |
* @type Custom Function | |
* @subtype Helper | |
* @return string | |
*/ | |
public string ObjectToString(object obj) | |
{ | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
new BinaryFormatter().Serialize(ms, obj); | |
return Convert.ToBase64String(ms.ToArray()); | |
} | |
} | |
/** | |
* De-Serialize a Base64 Serialized Object into an Object Again | |
* | |
* @var string Base64 Encoded | |
* @type Custom Function | |
* @subtype Helper | |
* @return object | |
*/ | |
public object StringToObject(string base64String) | |
{ | |
byte[] bytes = Convert.FromBase64String(base64String); | |
using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) | |
{ | |
ms.Write(bytes, 0, bytes.Length); | |
ms.Position = 0; | |
return new BinaryFormatter().Deserialize(ms); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment