问题
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?
回答1:
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
回答2:
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;
来源:https://stackoverflow.com/questions/27817266/how-to-correctly-use-urlencode-and-decode