检查是否给出完整路径

hs2*_*s2d 97 .net c# validation path

有没有一种方法可以检查给定路径是否为完整路径?现在我这样做:

if (template.Contains(":\\")) //full path already given
{
}
else //calculate the path from local assembly
{
}
Run Code Online (Sandbox Code Playgroud)

但是必须有更优雅的方式来检查这个?

det*_*lor 132

试试用System.IO.Path.IsPathRooted吗?它也返回true绝对路径.

System.IO.Path.IsPathRooted(@"c:\foo"); // true
System.IO.Path.IsPathRooted(@"\foo"); // true
System.IO.Path.IsPathRooted("foo"); // false

System.IO.Path.IsPathRooted(@"c:1\foo"); // surprisingly also true
System.IO.Path.GetFullPath(@"c:1\foo");// returns "[current working directory]\1\foo"
Run Code Online (Sandbox Code Playgroud)

  • 为什么第二个例子是绝对路径? (12认同)
  • 第二条路径不是绝对的,但它是根深蒂固的.前导斜杠表示系统的根. (3认同)
  • @SmirkinGherkin那么有根路径和绝对路径有什么区别? (3认同)
  • 根据 [文档](http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,807960f08fca497d) '测试给定的路径是否包含根。如果路径以反斜杠 ("\") 或驱动器号和冒号 (":") 开头,则该路径被认为是根路径。所以不解释差异,而是解释术语。 (2认同)

wei*_*eir 27

Path.IsPathRooted(path)
&& !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
Run Code Online (Sandbox Code Playgroud)

以上条件:

  • 不需要文件系统权限
  • false在大多数情况下返回格式path无效(而不是抛出异常)
  • true仅在path包含音量时返回

在OP提出的情况下,它可能比早期答案中的条件更合适.与上述条件不同:

  • path == System.IO.Path.GetFullPath(path)抛出异常而不是false在这些场景中返回:
    • 调用者没有所需的权限
    • 系统无法检索绝对路径
    • path包含冒号(":"),该冒号不是卷标识符的一部分
    • 指定的路径,文件名或两者都超过系统定义的最大长度
  • System.IO.Path.IsPathRooted(path)true如果path以单个目录分隔符开头,则返回.

最后,这是一个包含上述条件的方法,并且还排除了剩余的可能异常:

public static bool IsFullPath(string path) {
    return !String.IsNullOrWhiteSpace(path)
        && path.IndexOfAny(System.IO.Path.GetInvalidPathChars().ToArray()) == -1
        && Path.IsPathRooted(path)
        && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
Run Code Online (Sandbox Code Playgroud)

编辑:EM0做了一个很好的评论和替代答案,解决了像C:和的路径的奇怪情况C:dir.为了帮助您决定如何处理这些路径,您可能需要深入了解MSDN - > Windows桌面应用程序 - > 开发 - > 桌面技术 - > 数据访问和存储 - > 本地文件系统 - - > 文件管理 - > 关于文件管理 - > 创建,删除和维护文件 - > 命名文件,路径和命名空间 - > 完全合格与相对路径

对于操作文件的Windows API函数,文件名通常可以相对于当前目录,而某些API需要完全限定的路径.如果文件名不是以下列之一开头,则该文件名与当前目录相关:

  • 任何格式的UNC名称,始终以两个反斜杠字符("\")开头.有关更多信息,请参阅下一节.
  • 带反斜杠的磁盘指示符,例如"C:\"或"d:\".
  • 单个反斜杠,例如"\ directory"或"\ file.txt".这也称为绝对路径.

如果文件名仅以磁盘指示符开头但不以冒号后面的反斜杠开头,则会将其解释为指定字母的驱动器上当前目录的相对路径.请注意,当前目录可能是也可能不是根目录,具体取决于在该磁盘上最近的"更改目录"操作期间设置的目录.此格式的示例如下:

  • "C:tmp.txt"指的是驱动器C上当前目录中名为"tmp.txt"的文件.
  • "C:tempdir\tmp.txt"是指驱动器C上当前目录的子目录中的文件.

[...]

  • 我喜欢这不会抛出无效路径,但它对于像"C:"和"C:dir"这样的路径返回true,这些路径由GetFullPath使用当前目录解析(所以它们不是绝对的).发布了一个回答错误的答案. (3认同)

Joe*_*Joe 15

尝试

System.IO.Path.IsPathRooted(template)
Run Code Online (Sandbox Code Playgroud)

适用于UNC路径和本地路径.

例如

Path.IsPathRooted(@"\\MyServer\MyShare\MyDirectory")  // returns true
Path.IsPathRooted(@"C:\\MyDirectory")  // returns true
Run Code Online (Sandbox Code Playgroud)


小智 12

老问题,但一个更适用的答案.如果需要确保卷包含在本地路径中,可以使用System.IO.Path.GetFullPath(),如下所示:

if (template == System.IO.Path.GetFullPath(template))
{
    ; //template is full path including volume or full UNC path
}
else
{
    if (useCurrentPathAndVolume)
        template = System.IO.Path.GetFullPath(template);
    else
        template = Assembly.GetExecutingAssembly().Location
}
Run Code Online (Sandbox Code Playgroud)

  • 这就是我所需要的,并且似乎更接近于原始问题,因为IsPathRooted'对于相对路径(不一定是绝对路径)返回true (3认同)

EM0*_*EM0 10

基于的答案:这不会引发无效路径,但也会返回false"C:","C:dirname"和"\ path"之类的路径.

public static bool IsFullPath(string path)
{
    if (string.IsNullOrWhiteSpace(path) || path.IndexOfAny(Path.GetInvalidPathChars()) != -1 || !Path.IsPathRooted(path))
        return false;

    string pathRoot = Path.GetPathRoot(path);
    if (pathRoot.Length <= 2 && pathRoot != "/") // Accepts X:\ and \\UNC\PATH, rejects empty string, \ and X:, but accepts / to support Linux
        return false;

    if (pathRoot[0] != '\\' || pathRoot[1] != '\\')
        return true; // Rooted and not a UNC path

    return pathRoot.Trim('\\').IndexOf('\\') != -1; // A UNC server name without a share name (e.g "\\NAME" or "\\NAME\") is invalid
}
Run Code Online (Sandbox Code Playgroud)

请注意,这会在Windows和Linux上返回不同的结果,例如"/ path"在Linux上是绝对的,但在Windows上则不是.

单元测试:

[Test]
public void IsFullPath()
{
    bool isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); // .NET Framework
    // bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // .NET Core

    // These are full paths on Windows, but not on Linux
    TryIsFullPath(@"C:\dir\file.ext", isWindows);
    TryIsFullPath(@"C:\dir\", isWindows);
    TryIsFullPath(@"C:\dir", isWindows);
    TryIsFullPath(@"C:\", isWindows);
    TryIsFullPath(@"\\unc\share\dir\file.ext", isWindows);
    TryIsFullPath(@"\\unc\share", isWindows);

    // These are full paths on Linux, but not on Windows
    TryIsFullPath(@"/some/file", !isWindows);
    TryIsFullPath(@"/dir", !isWindows);
    TryIsFullPath(@"/", !isWindows);

    // Not full paths on either Windows or Linux
    TryIsFullPath(@"file.ext", false);
    TryIsFullPath(@"dir\file.ext", false);
    TryIsFullPath(@"\dir\file.ext", false);
    TryIsFullPath(@"C:", false);
    TryIsFullPath(@"C:dir\file.ext", false);
    TryIsFullPath(@"\dir", false); // An "absolute", but not "full" path

    // Invalid on both Windows and Linux
    TryIsFullPath(null, false, false);
    TryIsFullPath("", false, false);
    TryIsFullPath("   ", false, false);
    TryIsFullPath(@"C:\inval|d", false, false);
    TryIsFullPath(@"\\is_this_a_dir_or_a_hostname", false, false);
    TryIsFullPath(@"\\is_this_a_dir_or_a_hostname\", false, !isWindows);
    TryIsFullPath(@"\\is_this_a_dir_or_a_hostname\\", false, !isWindows);
}

private static void TryIsFullPath(string path, bool expectedIsFull, bool expectedIsValid = true)
{
    Assert.AreEqual(expectedIsFull, PathUtils.IsFullPath(path), "IsFullPath('" + path + "')");

    if (expectedIsFull)
    {
        Assert.AreEqual(path, Path.GetFullPath(path));
    }
    else if (expectedIsValid)
    {
        Assert.AreNotEqual(path, Path.GetFullPath(path));
    }
    else
    {
        Assert.That(() => Path.GetFullPath(path), Throws.Exception);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很高兴看到人们仍在使用它并发现新的边缘情况@Carl 更新了代码并进行了测试! (3认同)

Wil*_*iam 6

要检查路径是否完全合格(MSDN)

public static bool IsPathFullyQualified(string path)
{
    var root = Path.GetPathRoot(path);
    return root.StartsWith(@"\\") || root.EndsWith(@"\");
}
Run Code Online (Sandbox Code Playgroud)

它比已经提出的要简单一些,对于诸如的驱动器相对路径,它仍然返回false C:foo。它的逻辑直接基于MSDN的“完全限定”定义,我还没有发现任何不当的示例。


但是有趣的是,.NET Core 2.1似乎有一种Path.IsPathFullyQualified使用内部方法的新方法PathInternal.IsPartiallyQualified(链接位置截至2018-04-17准确)。

为了使后篇和更好地自我完善,这里是后者的实现,以供参考:

internal static bool IsPartiallyQualified(ReadOnlySpan<char> path)
{
    if (path.Length < 2)
    {
        // It isn't fixed, it must be relative.  There is no way to specify a fixed
        // path with one character (or less).
        return true;
    }

    if (IsDirectorySeparator(path[0]))
    {
        // There is no valid way to specify a relative path with two initial slashes or
        // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
        return !(path[1] == '?' || IsDirectorySeparator(path[1]));
    }

    // The only way to specify a fixed path that doesn't begin with two slashes
    // is the drive, colon, slash format- i.e. C:\
    return !((path.Length >= 3)
        && (path[1] == VolumeSeparatorChar)
        && IsDirectorySeparator(path[2])
        // To match old behavior we'll check the drive character for validity as the path is technically
        // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
        && IsValidDriveChar(path[0]));
}
Run Code Online (Sandbox Code Playgroud)


Myk*_*ych 5

这是我使用的解决方案

public static bool IsFullPath(string path)
{
    try
    {
        return Path.GetFullPath(path) == path;
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

它的工作方式如下:

IsFullPath(@"c:\foo"); // true
IsFullPath(@"C:\foo"); // true
IsFullPath(@"c:\foo\"); // true
IsFullPath(@"c:/foo"); // false
IsFullPath(@"\foo"); // false
IsFullPath(@"foo"); // false
IsFullPath(@"c:1\foo\"); // false
Run Code Online (Sandbox Code Playgroud)

  • 它为以下路径返回错误的结果:`C:\foo\..\foo` 或 `C:\foo\.\.\.` (2认同)

ser*_*gtk 5

从 .NET Core 2.1/NET Standard 2.1 开始,您可以调用以下方法:

Path.IsPathFullyQualified(@"c:\foo")
Run Code Online (Sandbox Code Playgroud)

MSDN 文档:Path.IsPathFullyQualified 方法

来自 MSDN 文档的有用引用如下:

此方法处理使用备用目录分隔符的路径。假设根路径(IsPathRooted(String))不是相对的,这是一个常见的错误。例如,“C:a”是相对于驱动器的,也就是说,它是针对 C: 的当前目录解析的(根目录,但相对)。“C:\a”是根目录而不是相对目录,即当前目录不用于修改路径。