如何在C#中用%20replace所有空格
我想用C#将一个string变成一个URL,在.NET框架中必须有一些东西可以帮助,对吗?
我相信你正在寻找HttpServerUtility.UrlEncode 。
 System.Web.HttpUtility.UrlEncode(string url) 
 另一种方法是使用Uri.EscapeUriString(stringToEscape) 。 
 我发现有用的System.Web.HttpUtility.UrlPathEncode(string str); 
它用%20replace空格,而不是用+。
 要正确地转义空格以及其他特殊字符,请使用System.Uri.EscapeDataString(string stringToEscape) 。 
 使用HttpServerUtility.UrlEncode 
HttpUtility.UrlEncode方法(string)
 我也需要这样做,从几年前发现这个问题,但问题标题和文本不匹配,使用Uri.EscapeDataString或UrlEncode (不要使用那个请!)通常没有意义,除非我们正在讨论将URL作为parameter passing给其他URL。 
(例如,在进行开放式身份validation,Azure AD等时传递callbackURL)
希望这是更实际的回答这个问题: 我想使用C#将一个string变成一个URL,在.NET框架中必须有一些东西应该帮助,对吧?
是的 – 两个函数有助于在C#中创buildURLstring
-  用于格式化URL的String.Format
-   Uri.EscapeDataString用于转义URL中的任何参数
这个代码
 String.Format("https://site/app/?q={0}&redirectUrl={1}", Uri.EscapeDataString("search for cats"), Uri.EscapeDataString("https://mysite/myapp/?state=from idp")) 
产生这个结果
 https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp 
 它可以安全地复制并粘贴到浏览器的地址栏或HTML A标签的src属性中,或用于curl或编码为QR码等。 
HttpServerUtility.HtmlEncode
从文档:
 String TestString = "This is a <Test String>."; String EncodedString = Server.HtmlEncode(TestString); 
更新:这实际上编码Html而不是url。 使用UrlEncode(TestString),因为每个人都可以阅读比我更好的说。 不要删除这个closures机会的人find这个线程,同时寻找HTML编码。
- 如何validation一个string是C ++中的有效IPv4地址?
- 一个C ++类的成员函数模板可以是虚拟的吗?
- 如何获得unit testing在x64平台上运行
- 在C#中转换位图PixelFormats
- Selenium错误 – 对远程WebDriver的HTTP请求在60秒后超时
- NUnit 3.0和Assert.Throws
- 如果我的传入date格式是YYYYMMDD,则在.NET中将string转换为date
- 推荐的ServiceStack API结构
- 在FormsAuthentication.SignOut()之后,Page.User.Identity.IsAuthenticated仍然为true。