【问题标题】:Is there a C# equivalent of python's os.path.normpath?是否有与 python 的 os.path.normpath 等效的 C#?
【发布时间】:2011-07-14 14:52:43
【问题描述】:

在 python 中,我获取一个原始字符串,然后将其传递给 os.path.normpath 以使其成为正确的路径名。它逃脱了我需要逃脱的所有东西,我不必担心。 C# 中是否有等价物?

这是一个 python sn-p。

myClassProjectPath = os.path.normpath(r"C:\Users\Documents\SharpDevelop Projects\Project With Spaces\MyClass\bin\Debug")

编辑:我担心斜线和空格。现在,我正在对代码中的路径进行硬编码,但它很快就会成为用户输入,所以我无法控制“/”与“\”

【问题讨论】:

  • 原始字符串和正确的路径名有什么区别?在 c# 中,两者都有 \\s 而不是 / 或 \,并且由于 .net 与“现代”文件名完全兼容,因此两者都可以包含空格等。
  • 使用/ 而不是\`。好多了。我的意思是,我什至无法让\` 正确显示...

标签: c# python path escaping


【解决方案1】:

也可以看看:

string normalizedPath = Path.GetDirectoryName(path);

这也将修复 /\

【讨论】:

  • 当我使用@ 使路径成为字符串文字时,这有效,如下所示。谢谢!
【解决方案2】:

您总是可以在前面添加一个 @ 来创建逐字字符串文字。

What's the @ in front of a string in C#?

【讨论】:

    【解决方案3】:

    尝试Path.Combine 没有任何东西的路径,或Path.ChangeExtension 它到Path.GetExtension。也许这些无用的程序之一(或另一个)正常化。

    除此之外:Pathdoesn’t 似乎包含该功能。

    或者,您可以自己编程。来自 Python 文档:

    Normalize a pathname. This collapses redundant separators and up-level references
    so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
    
    It does not normalize the case (use normcase() for that). On Windows, it converts
    forward slashes to backward slashes. It should be understood that this may change
    the meaning of the path if it contains symbolic links!
    

    【讨论】:

      【解决方案4】:

      我认为你们都可以使用

      string s = s.Replace(@"\", @"\\");
      

      string path = @"C:\Users\Documents\SharpDevelop Projects\Project With Spaces\MyClass\bin\Debug";
      

      how to automatically escape the path 找到这些答案。

      【讨论】:

      • 嗯。似乎照顾斜线而不是空格?我正在使用 SharpDevelop。当我调试并看到路径变量时,它会在第一个空格后切断。
      • 您的代码中可能还有其他问题。你能给这个问题更多的背景吗?
      • 嗯。你说的对。我刚刚尝试了一个简单的“Hello World”,它也处理了空间。如果我不能很快弄清楚,我会更多地研究我的具体代码并发布。感谢您的帮助!
      猜你喜欢
      • 2011-02-09
      • 2015-07-28
      • 2010-12-03
      • 2010-11-30
      • 2019-07-22
      • 2013-02-04
      • 2012-11-21
      • 2021-04-30
      • 2017-01-01
      相关资源
      最近更新 更多