【问题标题】:How do I replace all the spaces with %20 in C#?如何在 C# 中用 %20 替换所有空格?
【发布时间】:2010-12-03 19:21:36
【问题描述】:

我想使用 C# 将字符串转换为 URL。 .NET 框架中一定有一些东西应该有所帮助,对吧?

【问题讨论】:

  • 此问题标题与问题不匹配。要在 C# 中用 %20(标题)替换所有空格,您可以使用 String.Replace(" ", "%20")。如果您正在构建一个 URL,您需要做的就是将一个 URL 值放入一个字符串中:string url = "https://site/app/?q=cats" 但是如果 OP 正在讨论将 URL 作为 GET 参数作为另一个 URL 的一部分传递,那么这完全是另外一回事,这本身就不同例如,将 URL 发送到 ASP.NET(或其他)中的 HTML 锚标记中。

标签: c# url urlencode


【解决方案1】:

另一种方法是使用Uri.EscapeUriString(stringToEscape)

【讨论】:

  • 不幸的是,此方法无法转义& 字符。
  • 它也不会逃逸=,也不会逃逸?。看来Uri.EscapeDataString() 是要走的路。
  • 它也没有逃脱#
【解决方案2】:

我相信你正在寻找HttpServerUtility.UrlEncode

System.Web.HttpUtility.UrlEncode(string url)

【讨论】:

  • 我认为Uri.EscapeUriString() 是适当的方法,如果我们必须对此保持虔诚:)
  • @StoyanDimov: EscapeUriString() 不会转义 &=?,所以 EscapeDataString() 似乎是可以使用的。
  • 有人编辑了这个问题以完全改变答案。我们should not use editing to change the meaning 的特定帖子。
  • @palswim 是的,但是“接受”的答案不能是您恢复的那个:System.Web.HttpUtility.UrlEncode 将空间编码为+ 而不是%20,所以这个是完全不正确的。
  • 错误答案-不要使用UrlEncode,因为它用+(而不是OP特别要求的%20)替换空格,这不是标准的URI方案。 JavaScript 中的decodeURIdecodeURIComponent 无法正确解码。使用Uri.EscapeDataString,它可以被 JavaScript 正确解码,以实现编码数据和 URI 的良好往返使用
【解决方案3】:

我发现有用的System.Web.HttpUtility.UrlPathEncode(string str);

它将空格替换为 %20 而不是 +。

【讨论】:

  • 至少在 4.0 中有。 System.Web.HttpUtility.UrlDecode("a%20b") 产生“a b”
  • 它可以工作,但不要使用它,因为它适用于浏览器。请改用 Uri.EscapeUriString(STRING)。 MSDN:“不要使用;仅用于浏览器兼容性。使用 UrlEncode。” msdn.microsoft.com/en-us/library/…
  • 我发现它很有帮助,因为我只想对 URL 的一部分进行编码,但仍然可以点击它。这些超出了预期:System.Uri.EscapeDataString(url) 和 HttpContext.Current.Server.UrlEncode(url)
  • 我需要将空格编码为 %20 而不是 + 才能成功发布到 Twitter。 UrlEncode(url) 将空格变成 +,因此不是我的问题的正确答案。
【解决方案4】:

要正确转义空格以及其他特殊字符,请使用System.Uri.EscapeDataString(string stringToEscape)

【讨论】:

  • 如果是comment is an actual answer,则需要有人回答这个问题。
  • 是的,这个处理空格,# 和 %,但是将 / 编码为 %2f
【解决方案5】:

正如对已批准故事的评论,HttpServerUtility.UrlEncode 方法将空格替换为 + 而不是 %20。 请改用以下两种方法之一:Uri.EscapeUriString()Uri.EscapeDataString()

示例代码:

HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");    
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"

【讨论】:

    【解决方案6】:

    【讨论】:

      【解决方案7】:

      我也需要这样做,多年前发现了这个问题,但问题标题和文本不太匹配,使用 Uri.EscapeDataStringUrlEncode(请不要使用那个!)不除非我们谈论将 URL 作为参数传递给其他 URL,否则通常是有意义的。

      (例如在做开放ID认证、Azure AD等时传递回调URL)

      希望这是对问题的更务实的回答:我想使用 C# 将字符串转换为 URL,.NET 框架中必须有一些东西应该有帮助,对吧?

      - 两个函数有助于在 C# 中制作 URL 字符串

      • String.Format 用于格式化 URL
      • 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 一起使用,或编码为二维码等。

      【讨论】:

      • JavaScript 等价物类似于"https://site/app/?q=" + encodeURIComponent("search for cats") + "&redirectUrl=" + encodeURIComponent("https://mysite/myapp/?state=from idp") 会产生相同的输出。
      【解决方案8】:
      【解决方案9】:

      以下代码将用单个 %20 字符替换重复的空格。

      例子:

      输入是:

      Code by Hitesh             Jain
      

      输出:

      Code%20by%20Hitesh%20Jain
      

      代码

      static void Main(string[] args)
      {
          Console.WriteLine("Enter a string");
          string str = Console.ReadLine();
          string replacedStr = null;
      
          // This loop will repalce all repeat black space in single space
          for (int i = 0; i < str.Length - 1; i++)
          {
              if (!(Convert.ToString(str[i]) == " " &&
                  Convert.ToString(str[i + 1]) == " "))
              {
                  replacedStr = replacedStr + str[i];
              }
          }
          replacedStr = replacedStr + str[str.Length-1]; // Append last character
          replacedStr = replacedStr.Replace(" ", "%20");
          Console.WriteLine(replacedStr);
          Console.ReadLine();
      }
      

      【讨论】:

        【解决方案10】:

        HttpServerUtility.HtmlEncode

        来自文档:

        String TestString = "This is a <Test String>.";
        String EncodedString = Server.HtmlEncode(TestString);
        

        但这实际上编码的是 HTML,而不是 URL。而是使用 UrlEncode(TestString)

        【讨论】:

        • OP 询问 URL 编码;不是 HTML 编码。
        • 不,这是用于 HTML 编码,而不是 URL 编码(顾名思义......)
        • 是的,你是对的,使用 UrlEncode() 编码 url - 这仅用于编码 Html 实体
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        相关资源
        最近更新 更多