Click here to Skip to main content
15,861,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, is there an equivalent to the PHP rawurlencode in C#? I've already tried
C#
HttpUtility.UrlEncode
and
C#
HttpUtility.UrlEncodeUnicode
but they're not the same.It shows problem when char like Space '(' ')' etc..
Posted

1 solution

Both methods show the space as +, so you can replace + with %20 after using UrlEncode:
C#
string yourStr = "your text here";
string encodedStr = HttpUtility.UrlEncode(yourStr).Replace("+", "%20");


If the above method doesn't encode enough chars, as you said in your comment, use this function:
C#
// first, add this to the top of your code file: using System.Text.RegularExpressions;
string UrlEncode(string url)
{
    Dictionary<string, string> toBeEncoded = new Dictionary<string, string>() { { "%", "%25" }, { "!", "%21" }, { "#", "%23" }, { " ", "%20" },
    { "$", "%24" }, { "&", "%26" }, { "'", "%27" }, { "(", "%28" }, { ")", "%29" }, { "*", "%2A" }, { "+", "%2B" }, { ",", "%2C" }, 
    { "/", "%2F" }, { ":", "%3A" }, { ";", "%3B" }, { "=", "%3D" }, { "?", "%3F" }, { "@", "%40" }, { "[", "%5B" }, { "]", "%5D" } };
    Regex replaceRegex = new Regex(@"[%!# $&'()*+,/:;=?@\[\]]");
    MatchEvaluator matchEval = match => toBeEncoded[match.Value];
    string encoded = replaceRegex.Replace(url, matchEval);
    return encoded;
}

And to encode the URL:
C#
string yourStr = "your text here";
string encodedStr = UrlEncode(yourStr);
 
Share this answer
 
v4
Comments
aboutjayesh 25-Oct-14 10:46am    
Thanks for your information.But still in the case of '(' ')' etc are not converted using HttpUtility.UrlEncodeUnicode.For Eg:i got the out put of HttpUtility.UrlEncodeUnicode is 52620+(1).JPG for the original name 52620 (1).JPG and when i tried with some online conversion it is like 52620%20%281%29.JPG
Thomas Daniels 25-Oct-14 10:52am    
I updated my answer, because the first version was not correct. Please see the new version.

In the new version, the parentheses will still be there (but the space is already encoded correctly), but parentheses are not really required to be encoded, so the answer as it is now will do the job.
aboutjayesh 25-Oct-14 11:11am    
I got that.But i need to convert it like 52620%20%281%29.JPG
Thomas Daniels 25-Oct-14 11:37am    
I updated my answer to create a method that does that.
aboutjayesh 25-Oct-14 11:45am    
Thank you..Going to try this (y)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900