How to create an equivalent to JavaScript encodeURIComponent in C#

1 Answer

0 votes
using System;
using System.Web;

class Program
{
    public static string EncodeURIComponent(string str) {
        string result;

        try {
            result = HttpUtility.UrlEncode(str) // Perform URL encoding
                           .Replace("+", "%20")  // Replace "+" with "%20"
                           .Replace("%21", "!")  // Replace "%21" with "!"
                           .Replace("%27", "'")  // Replace "%27" with "'"
                           .Replace("%28", "(")  // Replace "%28" with "("
                           .Replace("%29", ")")  // Replace "%29" with ")"
                           .Replace("%7E", "~"); // Replace "%7E" with "~"
        }
        catch (Exception) {
            result = str; // Fallback to the original string in case of error
        }

        return result;
    }

    static void Main(string[] args)
    {
        string str = "https://www.seek4info.com/search.php?query=seo";

        // Encode the URL
        string encodedStr = EncodeURIComponent(str);

        Console.WriteLine(encodedStr);
    }
}



/*
run:

https%3a%2f%2fwww.seek4info.com%2fsearch.php%3fquery%3dseo

*/

 



answered Apr 13, 2025 by avibootz
...