C# 代码可以运行的不同环境对于文件和目录路径必须是什么样子有不同的约定/规则。
一个常见的示例是分隔目录级别的字符。
在 Windows 上,它是\
,在Linux上,它是/
,还有其他(也是未来的)系统可能遵循不同的规则。
因此,为了创建健壮的代码,建议始终使用Path.DirectorySeparatorChar https://learn.microsoft.com/de-de/dotnet/api/system.io.path.directoryseparatorchar?view=netframework-4.7.2(或者,当然,使用辅助方法,例如Path.Combine https://learn.microsoft.com/de-de/dotnet/api/system.io.path.combine?view=netframework-4.7.2)而不是硬编码特定的目录分隔符。
现在,在各种系统上,有一些“伪目录名称”可以在路径中使用:
-
.
代表当前目录
-
..
代表父目录,即当前目录的上一级
虽然这些在 Windows 和 Linux 上恰好是相同的,但其他环境(可以实现 Mono 来运行)可能会遵循不同的语法。
我不想对这些伪目录名称进行硬编码。我如何在运行时检索它们?
我不认为这是一个问题。/
适用于 Windows、Unix 和 Linux。同样适用于..
and .
。它也是统一命名约定用于网络路径。
在 Mono 的实现中Path
class ..
and .
是偶数硬编码的 https://github.com/mono/mono/blob/master/mcs/class/corlib/System.IO/Path.cs。如果底层框架甚至这样做的话,我认为避免硬编码没有任何意义。
Excerpt:
internal static void CheckSearchPattern(String searchPattern)
{
int index;
while ((index = searchPattern.IndexOf("..", StringComparison.Ordinal)) != -1) {
if (index + 2 == searchPattern.Length) // Terminal ".." . Files names cannot end in ".."
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSearchPattern"));
if ((searchPattern[index+2] == DirectorySeparatorChar)
|| (searchPattern[index+2] == AltDirectorySeparatorChar))
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSearchPattern"));
searchPattern = searchPattern.Substring(index + 2);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)