是否存在与系统无关的方法来确定表示当前目录和父目录级别的字符串? [英] Is there a system-agnostic way to determine strings that represent the current and the parent directory level?

查看:107
本文介绍了是否存在与系统无关的方法来确定表示当前目录和父目录级别的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在其中运行C#代码的不同环境对文件和目录路径的外观必须具有不同的约定/规则.

Different environments that C# code can be run in have different conventions/rules for what file and directory paths must look like.

一个常见的示例是分隔目录级别的字符. 在Windows上是\,在Linux上是/,而其他(也是将来的)系统可能遵循甚至不同的规则.

A common example is the character that separates directory levels. On Windows, it is \, on Linux, it is /, and still other (also future) systems may follow even different rules.

要创建健壮的代码,建议始终使用 Path.Combine ),而不是硬编码特定的目录分隔符.

To create robust code, it is therefore adviseable to always use Path.DirectorySeparatorChar (or, of course, using helper methods such as Path.Combine) rather than hard-coding a particular directory separator character.

现在,在各种系统上,可以在路径中使用一些伪目录名称":

Now, on various systems, there are some "pseudo-directory names" that can be used in paths:

  • .代表当前目录
  • ..代表父目录,即从当前目录向上一级
  • . represents the current directory
  • .. represents the parent directory, i.e. one level up from the current directory

尽管在Windows和Linux上它们恰好相同,但其他环境(可以实现Mono的运行环境)在这里可能会采用不同的语法.

While these happen to be the same on Windows and on Linux, other environments (that Mono could be implemented to run on) might follow a different syntax here.

我不想对这些伪目录名称进行硬编码.如何在运行时检索它们?

推荐答案

我认为这不是问题. /在Windows,Unix和Linux上均可使用. ...相同.它也是用于网络路径的统一命名约定的一部分.

I don't think this is an issue. / works on Windows, Unix and Linux. Same for .. and .. It is also part of the Uniform Naming Convention that is used for network paths.

在Mono对Path...的实现中,甚至

In Mono's implementation of the Path class .. and . are even hardcoded. I don't see any sense in avoidance of hardcoding if the underlying framework even does it.

节选:

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);
    }
}

这篇关于是否存在与系统无关的方法来确定表示当前目录和父目录级别的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆