When it comes to encoding special characters with reference
to URLs, we can easily make use of the functions that have been defined inside
System.Web.dll assembly.
Although this is the most straight forward hassle free way
to encode a string to make it compatible in a HTTP context, in some scenarios
we don’t get that privilege automatically (e.g. non web applications).
I ran into such scenario when I was developing a SQL Server
user defined function from VS 2010.
The special problem in that occasion was that when you add an assembly reference in a SQL
CLR project the reference is fetched from the GAC in data base server.
Microsoft have added a set of assemblies which they have
identified as safe assemblies to be referenced by a T-SQL function to the
GAC giving us the ability to use the functionality defined in those classes.
But unfortunately System.Web.dll is not one of them.
So what will be the work around, an another function we can use
for URL encoding can be found inside System.Uri name space, which fortunately resides
inside System.dll.
OK, so how to use it to only encode URL special characters!!
Simple just use the power of “Regular Expressions”.
Here is the function I wrote.
private static string EncodeUrl(string toEncode)
{
const string pattern = "[$&+,/:;=?@]";
var match = Regex.Match(toEncode, pattern);
while(match.Success)
{
toEncode = toEncode.Replace(match.Value, Uri.EscapeDataString(match.Value));
match = Regex.Match(toEncode, pattern);
}
return toEncode;
}
The
function checks the passed string repeatedly until all special characters
are replaced with their respective encoded values.
The combination of Regex.Match and string Replace functions make sure that only the characters that are defined in the regular expression pattern are replaced.