Path.IsPathRooted Метод

Определение

Возвращает значение, показывающее, содержит ли путь к файлу корневую папку.

Перегрузки

IsPathRooted(ReadOnlySpan<Char>)

Возвращает значение, которое показывает, содержит ли указанный диапазон символов, являющийся путем к файлу, корневую папку.

IsPathRooted(String)

Возвращает значение, показывающее, содержит ли указанная строка пути корневую папку.

Комментарии

Корневой путь — это путь к файлу, фиксированный для определенного диска или UNC-пути; он отличается от пути относительно текущего диска или рабочего каталога. Например, в системах Windows корневой путь начинается с обратной косой черты (например, "\Documents") или буквы диска и двоеточия (например, "C:Documents").

Обратите внимание, что корневые пути могут быть абсолютными (то есть полными) или относительными. Абсолютный корневой путь — это полный путь из корня диска в конкретный каталог. Относительный корневой путь указывает диск, но его полный путь разрешается в текущем каталоге. В следующем примере демонстрируется это различие.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string relative1 = "C:Documents"; 
        ShowPathInfo(relative1);

        string relative2 = "/Documents";
        ShowPathInfo(relative2);

        string absolute = "C:/Documents";
        ShowPathInfo(absolute);
    }

    private static void ShowPathInfo(string path)
    {
        Console.WriteLine($"Path: {path}");
        Console.WriteLine($"   Rooted: {Path.IsPathRooted(path)}");
        Console.WriteLine($"   Fully qualified: {Path.IsPathFullyQualified(path)}");
        Console.WriteLine($"   Full path: {Path.GetFullPath(path)}");
        Console.WriteLine();
    }
}
// The example displays the following output when run on a Windows system:
//    Path: C:Documents
//        Rooted: True
//        Fully qualified: False
//        Full path: c:\Users\user1\Documents\projects\path\ispathrooted\Documents
//
//    Path: /Documents
//       Rooted: True
//       Fully qualified: False
//       Full path: c:\Documents
//
//    Path: C:/Documents
//       Rooted: True
//       Fully qualified: True
//       Full path: C:\Documents
Imports System.IO

Module Program
    Public Sub Main()
        Dim relative1 As String = "C:Documents" 
        ShowPathInfo(relative1)

        Dim relative2 As String = "C:Documents" 
        ShowPathInfo(relative2)

        Dim absolute As String = "C:/Documents"
        ShowPathInfo(absolute)
    End Sub

    Private Sub ShowPathInfo(filepath As String)
        Console.WriteLine($"Path: {filepath}")
        Console.WriteLine($"   Rooted: {Path.IsPathRooted(filepath)}")
        Console.WriteLine($"   Fully qualified: {Path.IsPathFullyQualified(filepath)}")
        Console.WriteLine($"   Full path: {Path.GetFullPath(filepath)}")
        Console.WriteLine()
    End Sub
End Module
' The example displays the following output when run on a Windows system:
'    Path: C:Documents
'        Rooted: True
'        Fully qualified: False
'        Full path: c:\Users\user1\Documents\projects\path\ispathrooted\Documents
'
'    Path: /Documents
'       Rooted: True
'       Fully qualified: False
'       Full path: c:\Documents
'
'    Path: C:/Documents
'       Rooted: True
'       Fully qualified: True
'       Full path: C:\Documents

IsPathRooted(ReadOnlySpan<Char>)

Исходный код:
Path.Unix.cs
Исходный код:
Path.Unix.cs
Исходный код:
Path.Unix.cs

Возвращает значение, которое показывает, содержит ли указанный диапазон символов, являющийся путем к файлу, корневую папку.

public:
 static bool IsPathRooted(ReadOnlySpan<char> path);
public static bool IsPathRooted (ReadOnlySpan<char> path);
static member IsPathRooted : ReadOnlySpan<char> -> bool
Public Shared Function IsPathRooted (path As ReadOnlySpan(Of Char)) As Boolean

Параметры

path
ReadOnlySpan<Char>

Проверяемый путь.

Возвращаемое значение

Значение true, если параметр path содержит корневую папку; в противном случае — значение false.

См. также раздел

Применяется к

IsPathRooted(String)

Исходный код:
Path.Unix.cs
Исходный код:
Path.Unix.cs
Исходный код:
Path.Unix.cs

Возвращает значение, показывающее, содержит ли указанная строка пути корневую папку.

public:
 static bool IsPathRooted(System::String ^ path);
public static bool IsPathRooted (string path);
public static bool IsPathRooted (string? path);
static member IsPathRooted : string -> bool
Public Shared Function IsPathRooted (path As String) As Boolean

Параметры

path
String

Проверяемый путь.

Возвращаемое значение

Значение true, если параметр path содержит корневую папку; в противном случае — значение false.

Исключения

платформа .NET Framework и .NET Core версий старше 2.1: path содержит один или несколько недопустимых символов, определенных в GetInvalidPathChars().

Примеры

В следующем примере показано, как IsPathRooted можно использовать метод для тестирования трех строк.

String^ fileName = "C:\\mydir\\myfile.ext";
String^ UncPath = "\\\\myPc\\mydir\\myfile";
String^ relativePath = "mydir\\sudir\\";
bool result;
result = Path::IsPathRooted( fileName );
Console::WriteLine( "IsPathRooted('{0}') returns {1}", fileName, result.ToString() );
result = Path::IsPathRooted( UncPath );
Console::WriteLine( "IsPathRooted('{0}') returns {1}", UncPath, result.ToString() );
result = Path::IsPathRooted( relativePath );
Console::WriteLine( "IsPathRooted('{0}') returns {1}", relativePath, result.ToString() );

// This code produces output similar to the following:
//
// IsPathRooted('C:\mydir\myfile.ext') returns True
// IsPathRooted('\\myPc\mydir\myfile') returns True
// IsPathRooted('mydir\sudir\') returns False
string fileName = @"C:\mydir\myfile.ext";
string UncPath = @"\\myPc\mydir\myfile";
string relativePath = @"mydir\sudir\";
bool result;

result = Path.IsPathRooted(fileName);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
    fileName, result);

result = Path.IsPathRooted(UncPath);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
    UncPath, result);

result = Path.IsPathRooted(relativePath);
Console.WriteLine("IsPathRooted('{0}') returns {1}",
    relativePath, result);

// This code produces output similar to the following:
//
// IsPathRooted('C:\mydir\myfile.ext') returns True
// IsPathRooted('\\myPc\mydir\myfile') returns True
// IsPathRooted('mydir\sudir\') returns False
Dim fileName As String = "C:\mydir\myfile.ext"
Dim UncPath As String = "\\myPc\mydir\myfile"
Dim relativePath As String = "mydir\sudir\"
Dim result As Boolean

result = Path.IsPathRooted(fileName)
Console.WriteLine("IsPathRooted('{0}') returns {1}", fileName, result)

result = Path.IsPathRooted(UncPath)
Console.WriteLine("IsPathRooted('{0}') returns {1}", UncPath, result)

result = Path.IsPathRooted(relativePath)
Console.WriteLine("IsPathRooted('{0}') returns {1}", relativePath, result)

' This code produces output similar to the following:
'
' IsPathRooted('C:\mydir\myfile.ext') returns True
' IsPathRooted('\\myPc\mydir\myfile') returns True
' IsPathRooted('mydir\sudir\') returns False

Комментарии

Метод IsPathRooted возвращает значение true , если первый символ является разделителем каталога, например "\", или если путь начинается с буквы диска и двоеточия (:). Например, он возвращает true такие path строки, как "\\MyDir\MyFile.txt", "C:\MyDir" или "C:MyDir". Возвращается false для path таких строк, как "MyDir".

Этот метод не проверяет, существует ли путь или имя файла.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к