gpt4 book ai didi

.net - 如何确定路径是否完全合格?

转载 作者:行者123 更新时间:2023-12-05 02:08:56 27 4
gpt4 key购买 nike

给定一条路径,我需要知道它是否是完全限定路径(绝对路径)。

我知道有一个名为 System.IO.Path.IsPathRooted 的方法,但它对以下路径返回 true:

  • C:文档
  • /文档

我看到了一个名为 IsPathFullyQualified 的方法,对此我很感兴趣,请参阅 here , 但不幸的是,.NET Framework 4.5 似乎无法识别它。那么 .NET 4.5 是否有任何等效方法?

最佳答案

Full disclaimer: I did not write this code myself and do not own any rights to it. This is based on the .NET Core Source by Microsoft. More info below.

TL;DR: 对于 Windows 系统,您可以将以下类添加到您的项目中,然后调用 PathEx.IsPathFullyQualified() 检查路径是否完整合格:

Public Class PathEx
Public Shared Function IsPathFullyQualified(path As String) As Boolean
If path Is Nothing Then
Throw New ArgumentNullException(NameOf(path))
End If

Return Not IsPartiallyQualified(path)
End Function

Private Shared Function IsPartiallyQualified(path As String) As Boolean
If path.Length < 2 Then
' It isn't fixed, it must be relative. There is no way to specify a fixed
' path with one character (or less).
Return True
End If

If IsDirectorySeparator(path.Chars(0)) Then
' 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 Not (path.Chars(1) = "?"c OrElse IsDirectorySeparator(path.Chars(1)))
End If

' 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 Not ((path.Length >= 3) AndAlso
(path.Chars(1) = IO.Path.VolumeSeparatorChar) AndAlso
IsDirectorySeparator(path.Chars(2)) AndAlso
IsValidDriveChar(path.Chars(0)))
' ^^^^^^^^^^^^^^^^
' 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.
End Function

Private Shared Function IsDirectorySeparator(c As Char) As Boolean
Return c = Path.DirectorySeparatorChar OrElse c = Path.AltDirectorySeparatorChar
End Function

Private Shared Function IsValidDriveChar(value As Char) As Boolean
Return (value >= "A"c AndAlso value <= "Z"c) OrElse
(value >= "a"c AndAlso value <= "z"c)
End Function
End Class

这段代码(和注释)来自哪里?

这是从 .NET Core Source Browser 中提取的它是公开可用的,适用于 .NET Framework,并转换为 VB.NET。

.NET Core 的 IsPathFullyQualified() method使用名为 IsPartiallyQualified() 的内部方法来检查路径是否完全限定(不是部分限定)。该内部方法对于不同的操作系统具有不同的逻辑。 This是上述代码所基于的 Windows 版本。

用法:

Console.WriteLine(PathEx.IsPathFullyQualified("C:Documents"))    ' False
Console.WriteLine(PathEx.IsPathFullyQualified("/Documents")) ' False
Console.WriteLine(PathEx.IsPathFullyQualified("C:\Documents")) ' True

关于.net - 如何确定路径是否完全合格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60365892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com