【问题标题】:Uri.AbsolutePath messes up path with spacesUri.AbsolutePath 用空格弄乱了路径
【发布时间】:2009-01-12 18:42:44
【问题描述】:

在 WinApp 中,我只是想从 Uri 对象中获取绝对路径:

Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;

如果我的原始路径中没有空格,这可以正常工作。如果那里有空格,则字符串会被破坏;例如 'Documents and settings' 变成 'Documents%20and%20Setting' 等等。

任何帮助将不胜感激!

编辑: LocalPath 而不是 AbsolutePath 成功了!

【问题讨论】:

  • 请注意:这是编码无知的罕见表现

标签: c# .net-2.0 system.net winapp


【解决方案1】:

这就是它应该的方式。这称为 URL 编码。它适用,因为 URL 中不允许有空格。

如果你想返回包含空格的路径,你必须调用类似:

string path = Server.URLDecode(myUri.AbsolutePath);

您无需导入任何内容即可在 Web 应用程序中使用它。如果出现错误,请尝试导入 System.Web.HttpServerUtility。或者,您可以这样称呼它:

string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);

【讨论】:

  • 听起来不错 - 我应该在 WinApp 中添加哪个参考?
  • sweet - 所以我认为 WinApps 没有类似的东西?
  • 感谢您的回答 - 在这种情况下,最好的解决方案是使用 LocalPath 而不是 AbsolutePath,因为它是一个 winapp,我不喜欢使用 Server 或 HttpContext。
【解决方案2】:

它按照应有的方式对其进行编码,您可能可以对其进行 UrlDecode 以用空格将其取回,但它并没有“损坏”它只是正确编码。

我不确定你在写什么,但要将它转换回 asp.net,它是 Server.UrlDecode(path)。如果它是 Windows 应用程序,您也可以使用 LocalPath,而不是 AbsolutePath。

【讨论】:

  • 我不确定你在写什么,但在 asp.net 中是 Server.UrlDecode(path);
  • 如果是 Windows 应用程序,您也可以使用 LocalPath,而不是 AbsolutePath。
【解决方案3】:

只需使用 uri.LocalPath 代替

【讨论】:

    【解决方案4】:

    Uri 还有几个静态方法 - EscapeDataString 和 EscapeUriString。

    Uri.EscapeDataString(uri.AbsolutePath) 也可以使用

    【讨论】:

    • 你的意思可能是 Uri.UnescapeDataString
    【解决方案5】:

    使用 HttpUtility:

     HttpUtility.UrlDecode(uri.AbsolutePath)
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      相关资源
      最近更新 更多