How to correctly use UrlEncode and Decode

2019-05-13 20:42发布

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?

2条回答
戒情不戒烟
2楼-- · 2019-05-13 21:02

Use the System.Uri class to properly encode a path: MSDN System.Uri

Try the below on your path and use the debugger to inspect:

        var myUri = new System.Uri("http://someurl.com/my special path + is this/page?param=2");
        var thePathAndQuery = myUri.PathAndQuery;
        var theAbsolutePath = myUri.AbsolutePath;
        var theAbsoluteUri = myUri.AbsoluteUri;
查看更多
Lonely孤独者°
3楼-- · 2019-05-13 21:14

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

查看更多
登录 后发表回答