
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
814
|
Chapter 14: Web
14.13 Escaping and Unescaping Data for the Web
Problem
You need to transform data for use in web operations from escaped to unescaped
format or vice versa for proper transmission. This escaping and unescaping should
follow the format outlined in RFC 2396—Uniform Resource Identifiers (URI):
Generic Syntax.
Solution
Use the Uri class static methods for escaping and unescaping data and Uris.
To escape data, use the static
Uri.EscapeDataString method as shown here:
string data = "<H1>My html</H1>";
Console.WriteLine("Original Data: {0}",data);
Console.WriteLine( );
// public static string EscapeDataString(string stringToEscape);
string escapedData = Uri.EscapeDataString(data);
Console.WriteLine("escaped Data: {0}",escapedData);
Console.WriteLine( );
// Output from above code is
//
// Original Data: <H1>My html</H1>
//
// Escaped Data: %3CH1%3EMy%20html%3C%2FH1%3E
To unescape the data, use the static Uri.UnescapeDataString method:
// public static string UnescapeDataString( string stringToUnescape);
string unescapedData = Uri.UnescapeDataString(escapedData);
Console.WriteLine("unescaped Data: {0}",data);
Console.WriteLine( );
// Output from above code is
//
// Unescaped Data: <H1>My html</H1>
To escape a Uri, use the static Uri.EscapeUriString method:
string uriString = "http://user:password@localhost:8080/www.abc.com/" ...