Search code examples
c#azureencodingurlencodeurldecode

How to correctly use UrlEncode and Decode


So I have a file I am uploading to azure blob storage:

C:\test folder\A+B\testfile.txt

and two extension methods that help encode my path to make sure it is given a valid azure storage blob name

    public static string AsUriPath(this string filePath)
    {
        return System.Web.HttpUtility.UrlPathEncode(filePath.Replace('\\', '/'));
    }
    public static string AsFilePath(this string uriPath)
    {
        return System.Web.HttpUtility.UrlDecode(uriPath.Replace('/', '\\'));
    }

So when upload the file I encode it AsUriPath and get the name test%20folder\A+B\testfile.txt but when I try to get this back as a file path I get test folder\A B\testfile.txt which is obviously not the same (the + has been dropped)

What's the correct way to use UrlEncode and UrlDecode to ensure you will get the same information decoded as you originally encoded?


Solution

  • It works if you use WebUtility.UrlEncode instead of HttpUtility.UrlPathEncode

    If you check out the docs on HttpUtility.UrlPathEncode you'll see that it states:

    Do not use; intended only for browser compatibility. Use UrlEncode.

    I've coded up a simple example which can be pasted into a console app (you'll need to reference the System.Web assembly)

    static void Main(string[] args)
    {
        string filePath = @"C:\test folder\A+B\testfile.txt";
        var encoded = WebUtility.UrlEncode(filePath.Replace('\\', '/'));
        var decoded = WebUtility.UrlDecode(encoded.Replace('/', '\\'));
        Console.WriteLine(decoded);
    }
    

    Run it here at this .NET Fiddle