encode url 兼容_如何正确使用UrlEncode和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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值