andrew4582

UrlEncode

Aug 18th, 2010
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1.         /// <summary>
  2.         /// Serializes the specified data, and returns an Url Token Encoded string
  3.         /// </summary>
  4.         public static string UrlEncode(object data) {
  5.             if(data == null) {
  6.                 throw new ArgumentNullException("data");
  7.             }
  8.  
  9.             BinaryFormatter formatter = new BinaryFormatter();
  10.             byte[] dataBytes;
  11.             /* Serialize the data to a byte array. */
  12.             using(MemoryStream stream = new MemoryStream()) {
  13.                 formatter.Serialize(stream,data);
  14.                 dataBytes = stream.ToArray();
  15.             }
  16.  
  17.             /* URL encode the result. */
  18.             return HttpServerUtility.UrlTokenEncode(dataBytes);
  19.         }
  20.         /// <summary>
  21.         /// Deserializes the Url Token Encoded string
  22.         /// </summary>
  23.         public static object UrlDecode(string value) {
  24.             return UrlDecode<object>(value);
  25.         }
  26.         /// <summary>
  27.         /// Deserializes the Url Token Encoded string
  28.         /// </summary>
  29.         public static T UrlDecode<T>(string value) {
  30.             if(value == null) {
  31.                 throw new ArgumentNullException("value");
  32.             }
  33.  
  34.             /* Decode the data. */
  35.             byte[] decoded = HttpServerUtility.UrlTokenDecode(value);
  36.  
  37.             /* Reinstantiate the object instance. */
  38.             BinaryFormatter formatter = new BinaryFormatter();
  39.             object deserialized;
  40.  
  41.             using(MemoryStream stream = new MemoryStream(decoded)) {
  42.                 deserialized = formatter.Deserialize(stream);
  43.             }
  44.  
  45.             return (T)deserialized;
  46.         }
Advertisement
Add Comment
Please, Sign In to add comment