Friday, August 22, 2008

Where is the rawurlencode of ASP.NET?

I could not find a function in ASP.NET that behaves like PHP's rawurlencode. System.Web.HttpUtility and HttpServerUtility both have UrlEncode and UrlPathEncode. So I created the function below to extend UrlEncode to manually encode the characters that kept the the filenames from working as an <a href path


/// <summary>
/// HttpUtility.UrlEncode() and Server.UrlEncode()
/// do not urlencode some special characters.
/// This procedure ensures that the file part of the
/// url returned is properly encoded
/// Used http://www.voormedia.com/en/tools/url-encoder-php-asp-urlencode.php
/// to see what characters urlencode to
/// Also http://en.wikipedia.org/wiki/Url_encoding
/// </summary>
/// <param name="Filename"></param>
/// <returns></returns>
public static string GetUrlEncodedFilename(string Filename)
{
string FileNameEncoded = "";
if (Filename != null)
{ FileNameEncoded = HttpUtility.UrlEncode(Filename);
//UrlEncode encodes spaces to pluses. http://forums.asp.net/t/1231078.aspx
FileNameEncoded = FileNameEncoded.Replace("+", "%20");
//Encode ' so the href specification does not terminate
FileNameEncoded = FileNameEncoded.Replace("'", "%27");
} return FileNameEncoded;
}

Here is an online HTML encoder I used to be able to format the code to show up correctly.

No comments: