简体   繁体   English

在c#中用%20转换/替换空格,反之亦然

[英]Convert/Replace space with %20 and vice versa in c#

Below is the code to create a zip file and to add files to it. 下面是创建zip文件并向其添加文件的代码。

Problem: Currently, when the zip file is created, the files present in it contains %20 instead of space which is one functionality.I have another requirement to replace %20 with space . 问题:目前,当创建zip文件时,其中存在的文件包含%20而不是space ,这是一个功能。我还有另一个要求用space替换%20 How to achieve this in below code. 如何在下面的代码中实现这一点。

Removed the code from the post. 从帖子中删除了代码。

Here is an example using the Uri static class: 以下是使用Uri静态类的示例:

var url = "http://www.somewhere.net/Thingy%20World.html";

var decoded = Uri.UnescapeDataString(url);
//decoded is currently 'http://www.somewhere.net/Thingy World.html'

var encoded = Uri.EscapeUriString(decoded);//back to encoded
//encoded is currently 'http://www.somewhere.net/Thingy%20World.html' 

This should help: 这应该有所帮助:

https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx

Unescaping data strings would be an easy way. 取消数据字符串将是一种简单的方法。 You could also look into Regex and Regex.Replace. 您还可以查看Regex和Regex.Replace。

Edit: Oh - and you can use EscapeDataString to place %20 into the string. 编辑:哦 - 你可以使用EscapeDataString将%20放入字符串中。 As for the Regex approach, you could try Regex encodeSpace = new Regex(" "]); 至于Regex方法,你可以试试Regex encodeSpace = new Regex(" "]); and then you can call a replace on your string string newStringWithNoSpaces = encodeSpace.Replace(oldString, "%20"); 然后你可以调用你的字符串string newStringWithNoSpaces = encodeSpace.Replace(oldString, "%20"); You can do something similar for the other direction. 你可以为另一个方向做类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM