Is there a system-agnostic way to determine string

2019-07-11 05:58发布

问题:

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

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.

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

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.

I do not want to hard-code these pseudo-directory names. How can I retrieve them at runtime?

回答1:

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.

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.

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


标签: c# mono