Path 类

定义

对包含文件或目录路径信息的 String 实例执行操作。Performs operations on String instances that contain file or directory path information. 这些操作是以跨平台的方式执行的。These operations are performed in a cross-platform manner.

public ref class Path abstract sealed
[System.Runtime.InteropServices.ComVisible(true)]
public static class Path
type Path = class
Public Class Path
继承
Path
属性

示例

下面的示例演示了 Path 类的一些主要成员。The following example demonstrates some of the main members of the Path class.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path1 = "c:\\temp\\MyTest.txt";
   String^ path2 = "c:\\temp\\MyTest";
   String^ path3 = "temp";
   if ( Path::HasExtension( path1 ) )
   {
      Console::WriteLine( "{0} has an extension.", path1 );
   }

   if (  !Path::HasExtension( path2 ) )
   {
      Console::WriteLine( "{0} has no extension.", path2 );
   }

   if (  !Path::IsPathRooted( path3 ) )
   {
      Console::WriteLine( "The string {0} contains no root information.", path3 );
   }

   Console::WriteLine( "The full path of {0} is {1}.", path3, Path::GetFullPath( path3 ) );
   Console::WriteLine( "{0} is the location for temporary files.", Path::GetTempPath() );
   Console::WriteLine( "{0} is a file available for use.", Path::GetTempFileName() );
   Console::WriteLine( "\r\nThe set of invalid characters in a path is:" );
   Console::WriteLine( "(Note that the wildcard characters '*' and '?' are not invalid.):" );
   Collections::IEnumerator^ myEnum = Path::InvalidPathChars->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Char c =  *safe_cast<Char^>(myEnum->Current);
      Console::WriteLine( c );
   }
}

using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path1 = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp\MyTest";
        string path3 = @"temp";

        if (Path.HasExtension(path1)) 
        {
            Console.WriteLine("{0} has an extension.", path1);
        }

        if (!Path.HasExtension(path2)) 
        {
            Console.WriteLine("{0} has no extension.", path2);
        }

        if (!Path.IsPathRooted(path3)) 
        {
            Console.WriteLine("The string {0} contains no root information.", path3);
        }

        Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3));
        Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath());
        Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName());

        /* This code produces output similar to the following:
         * c:\temp\MyTest.txt has an extension.
         * c:\temp\MyTest has no extension.
         * The string temp contains no root information.
         * The full path of temp is D:\Documents and Settings\cliffc\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\temp.
         * D:\Documents and Settings\cliffc\Local Settings\Temp\8\ is the location for temporary files.
         * D:\Documents and Settings\cliffc\Local Settings\Temp\8\tmp3D.tmp is a file available for use.
         */
    }
}
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path1 As String = "c:\temp\MyTest.txt"
        Dim path2 As String = "c:\temp\MyTest"
        Dim path3 As String = "temp"

        If Path.HasExtension(path1) Then
            Console.WriteLine("{0} has an extension.", path1)
        End If

        If Path.HasExtension(path2) = False Then
            Console.WriteLine("{0} has no extension.", path2)
        End If

        If Path.IsPathRooted(path3) = False Then
            Console.WriteLine("The string {0} contains no root information.", path3)
        End If

        Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3))
        Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath())
        Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName())

        ' This code produces output similar to the following:
        ' c:\temp\MyTest.txt has an extension.
        ' c:\temp\MyTest has no extension.
        ' The string temp contains no root information.
        ' The full path of temp is D:\Documents and Settings\cliffc\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\temp.
        ' D:\Documents and Settings\cliffc\Local Settings\Temp\8\ is the location for temporary files.
        ' D:\Documents and Settings\cliffc\Local Settings\Temp\8\tmp3D.tmp is a file available for use.

    End Sub
End Class

注解

路径是提供文件或目录的位置的字符串。A path is a string that provides the location of a file or directory. 路径不一定指向磁盘上的位置;例如,路径可能映射到内存中或设备上的某个位置。A path does not necessarily point to a location on disk; for example, a path might map to a location in memory or on a device. 路径的准确格式由当前平台决定。The exact format of a path is determined by the current platform. 例如,在某些系统中,路径可以从驱动器或卷号开始,而此元素在其他系统中不存在。For example, on some systems, a path can start with a drive or volume letter, while this element is not present in other systems. 在某些系统上,文件路径可以包含扩展,这表示文件中存储的信息的类型。On some systems, file paths can contain extensions, which indicate the type of information stored in the file. 文件扩展名的格式依赖于平台;例如,某些系统将扩展限制为三个字符,而其他系统则不限制。The format of a file name extension is platform-dependent; for example, some systems limit extensions to three characters, and others do not. 当前平台还决定了用于分隔路径中的元素的字符集,以及指定路径时不能使用的字符集。The current platform also determines the set of characters used to separate the elements of a path, and the set of characters that cannot be used when specifying paths. 由于这些差异,Path 类的字段以及 Path 类的某些成员的确切行为取决于平台。Because of these differences, the fields of the Path class as well as the exact behavior of some members of the Path class are platform-dependent.

路径可以包含绝对或相对位置信息。A path can contain absolute or relative location information. 绝对路径完全指定位置:可以唯一地标识文件或目录,而不考虑当前位置。Absolute paths fully specify a location: the file or directory can be uniquely identified regardless of the current location. 相对路径指定部分位置:在定位使用相对路径指定的文件时,当前位置用作起始点。Relative paths specify a partial location: the current location is used as the starting point when locating a file specified with a relative path. 若要确定当前目录,请调用 Directory.GetCurrentDirectoryTo determine the current directory, call Directory.GetCurrentDirectory.

.NET Core 1.1 及更高版本和 .NET Framework 4.6.2 及更高版本还支持访问作为设备名称的文件系统对象,例如 "\? \C:"。.NET Core 1.1 and later versions and .NET Framework 4.6.2 and later versions also support access to file system objects that are device names, such as "\?\C:".

有关 Windows 上的文件路径格式的详细信息,请参阅windows 系统上的文件路径格式For more information on file path formats on Windows, see File path formats on Windows systems.

Path 类的大多数成员不与文件系统进行交互,并且不验证路径字符串指定的文件是否存在。Most members of the Path class do not interact with the file system and do not verify the existence of the file specified by a path string. 修改路径字符串的 Path 类成员(如 ChangeExtension)对文件系统中的文件名称不起作用。Path class members that modify a path string, such as ChangeExtension, have no effect on names of files in the file system. Path 成员将验证指定路径字符串的内容,如果字符串包含在路径字符串中无效的字符,则会引发 ArgumentException 异常,如 GetInvalidPathChars 方法返回的字符中所定义的那样。Path members do, however, validate the contents of a specified path string, and throw an ArgumentException exception if the string contains characters that are not valid in path strings, as defined in the characters returned from the GetInvalidPathChars method. 例如,在基于 Windows 的桌面平台上,无效路径字符可能包括引号(")、小于(<)、大于号(>)、管道(|)、backspace (\b)、null (\ 0)和 Unicode 字符16到18以及20到25。For example, on Windows-based desktop platforms, invalid path characters might include quote ("), less than (<), greater than (>), pipe (|), backspace (\b), null (\0), and Unicode characters 16 through 18 and 20 through 25.

使用 Path 类的成员可以快速轻松地执行常见操作,例如确定文件扩展名是否为路径的一部分,以及将两个字符串组合成一个路径名称。The members of the Path class enable you to quickly and easily perform common operations such as determining whether a file name extension is part of a path, and combining two strings into one path name.

Path 类的所有成员都是静态的,因此可以在没有路径实例的情况下调用。All members of the Path class are static and can therefore be called without having an instance of a path.

备注

在接受路径作为输入字符串的成员中,该路径必须格式正确,否则会引发异常。In members that accept a path as an input string, that path must be well-formed or an exception is raised. 例如,如果路径是完全限定的,但以空格开头,则不会在类的方法中剪裁路径。For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. 因此,路径格式不正确,并引发异常。Therefore, the path is malformed and an exception is raised. 同样,路径或路径的组合不能完全限定两次。Similarly, a path or a combination of paths cannot be fully qualified twice. 例如,在大多数情况下,"c:\temp c:\windows" 也会引发异常。For example, "c:\temp c:\windows" also raises an exception in most cases. 使用接受路径字符串的方法时,请确保路径格式正确。Ensure that your paths are well-formed when using methods that accept a path string.

在接受路径的成员中,路径可以引用文件或只引用目录。In members that accept a path, the path can refer to a file or just a directory. 指定的路径还可以引用服务器和共享名称的相对路径或通用命名约定(UNC)路径。The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. 例如,以下所有内容都是可接受的路径:For example, all the following are acceptable paths:

  • "c:\\MyDir\" 中C#的 "\MyFile.txt" 或 "c:\MyDir\MyFile.txt" 中的 Visual Basic。"c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic.

  • Visual Basic 中的 "c:\C#\MyDir" 或 "c:\MyDir"。"c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic.

  • Visual Basic 中的 "MyDir\C#\MySubdir" 或 "MyDir\MySubDir"。"MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic.

  • \中的 "\\\\MyServer\C#\MyShare" 或 "Visual Basic \MyServer\MyShare"。"\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic.

由于所有这些操作都是针对字符串执行的,因此无法验证结果在所有方案中是否有效。Because all these operations are performed on strings, it is impossible to verify that the results are valid in all scenarios. 例如,GetExtension 方法会分析传递给它的字符串,并返回该字符串的扩展名。For example, the GetExtension method parses a string that you pass to it and returns the extension from that string. 但是,这并不意味着磁盘上存在具有该扩展名的文件。However, this does not mean that a file with that extension exists on the disk.

有关常见 i/o 任务的列表,请参阅常见 I/o 任务For a list of common I/O tasks, see Common I/O Tasks.

字段

AltDirectorySeparatorChar

提供平台特定的替换字符,该替换字符用于在反映分层文件系统组织的路径字符串中分隔目录级别。Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization.

DirectorySeparatorChar

提供平台特定的字符,该字符用于在反映分层文件系统组织的路径字符串中分隔目录级别。Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization.

InvalidPathChars

提供平台特定的字符数组,这些字符不能在传递到 Path 类的成员的路径字符串自变量中指定。Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the Path class.

PathSeparator

用于在环境变量中分隔路径字符串的平台特定的分隔符。A platform-specific separator character used to separate path strings in environment variables.

VolumeSeparatorChar

提供平台特定的卷分隔符。Provides a platform-specific volume separator character.

方法

ChangeExtension(String, String)

更改路径字符串的扩展名。Changes the extension of a path string.

Combine(String, String)

将两个字符串组合成一个路径。Combines two strings into a path.

Combine(String, String, String)

将三个字符串组合成一个路径。Combines three strings into a path.

Combine(String, String, String, String)

将四个字符串组合成一个路径。Combines four strings into a path.

Combine(String[])

将字符串数组组合成一个路径。Combines an array of strings into a path.

EndsInDirectorySeparator(ReadOnlySpan<Char>)

返回一个值,该值指示指定为只读范围的路径是否以目录分隔符结尾。Returns a value that indicates whether the path, specified as a read-only span, ends in a directory separator.

EndsInDirectorySeparator(String)

返回一个值,该值指示指定的路径是否以目录分隔符结尾。Returns a value that indicates whether the specified path ends in a directory separator.

GetDirectoryName(ReadOnlySpan<Char>)

返回由字符范围表示的指定路径的目录信息。Returns the directory information for the specified path represented by a character span.

GetDirectoryName(String)

返回指定路径字符串的目录信息。Returns the directory information for the specified path string.

GetExtension(ReadOnlySpan<Char>)

返回由只读字符范围表示的文件路径的扩展名。Returns the extension of a file path that is represented by a read-only character span.

GetExtension(String)

返回指定路径字符串的扩展名(包括句点“.”)。Returns the extension (including the period ".") of the specified path string.

GetFileName(ReadOnlySpan<Char>)

返回由只读字符范围表示的文件路径的文件名和扩展名。Returns the file name and extension of a file path that is represented by a read-only character span.

GetFileName(String)

返回指定路径字符串的文件名和扩展名。Returns the file name and extension of the specified path string.

GetFileNameWithoutExtension(ReadOnlySpan<Char>)

返回文件名,该文件名不带由只读字符范围表示的文件路径扩展名。Returns the file name without the extension of a file path that is represented by a read-only character span.

GetFileNameWithoutExtension(String)

返回不具有扩展名的指定路径字符串的文件名。Returns the file name of the specified path string without the extension.

GetFullPath(String)

返回指定路径字符串的绝对路径。Returns the absolute path for the specified path string.

GetFullPath(String, String)

返回完全限定的基本路径和相对路径的绝对路径。Returns an absolute path from a fully qualified base path and a relative path.

GetInvalidFileNameChars()

获取包含不允许在文件名中使用的字符的数组。Gets an array containing the characters that are not allowed in file names.

GetInvalidPathChars()

获取包含不允许在路径名中使用的字符的数组。Gets an array containing the characters that are not allowed in path names.

GetPathRoot(ReadOnlySpan<Char>)

从指定字符范围包含的路径中获取根目录信息。Gets the root directory information from the path contained in the specified character span.

GetPathRoot(String)

从指定字符串包含的路径中获取根目录信息。Gets the root directory information from the path contained in the specified string.

GetRandomFileName()

返回随机文件夹名或文件名。Returns a random folder name or file name.

GetRelativePath(String, String)

返回从一个路径到另一个路径的相对路径。Returns a relative path from one path to another.

GetTempFileName()

在磁盘上创建磁唯一命名的零字节的临时文件并返回该文件的完整路径。Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.

GetTempPath()

返回当前用户的临时文件夹的路径。Returns the path of the current user's temporary folder.

HasExtension(ReadOnlySpan<Char>)

确定指定字符范围表示的路径是否包含文件扩展名。Determines whether the path represented by the specified character span includes a file name extension.

HasExtension(String)

确定路径是否包括文件扩展名。Determines whether a path includes a file name extension.

IsPathFullyQualified(ReadOnlySpan<Char>)

返回一个值,该值指示由指定字符范围表示的文件路径是否固定到特定驱动器或 UNC 路径。Returns a value that indicates whether the file path represented by the specified character span is fixed to a specific drive or UNC path.

IsPathFullyQualified(String)

返回一个值,该值指示指定的文件路径是否固定到特定驱动器或 UNC 路径。Returns a value that indicates whether the specified file path is fixed to a specific drive or UNC path.

IsPathRooted(ReadOnlySpan<Char>)

返回一个值,该值指示表示文件路径的指定字符范围是否包含根。Returns a value that indicates whether the specified character span that represents a file path contains a root.

IsPathRooted(String)

返回一个值,该值指示指定的路径字符串是否包含根。Returns a value indicating whether the specified path string contains a root.

Join(ReadOnlySpan<Char>, ReadOnlySpan<Char>)

将两个路径组件连接到一个路径中。Concatenates two path components into a single path.

Join(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)

将三个路径组件连接到一个路径中。Concatenates three path components into a single path.

Join(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)

将四个路径组件连接到一个路径中。Concatenates four path components into a single path.

Join(String, String)

将两个路径连接到一个路径中。Concatenates two paths into a single path.

Join(String, String, String)

将三个路径连接到一个路径中。Concatenates three paths into a single path.

Join(String, String, String, String)

将四个路径连接到一个路径中。Concatenates four paths into a single path.

Join(String[])

将路径数组连接到一个路径中。Concatenates an array of paths into a single path.

TrimEndingDirectorySeparator(ReadOnlySpan<Char>)

剪裁一个超出指定路径根目录的尾随目录分隔符。Trims one trailing directory separator beyond the root of the specified path.

TrimEndingDirectorySeparator(String)

剪裁一个超出指定路径根目录的尾随目录分隔符。Trims one trailing directory separator beyond the root of the specified path.

TryJoin(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, Span<Char>, Int32)

尝试将两个路径组件连接到一个预分配的字符范围,并返回一个值,该值指示操作是否成功。Attempts to concatenate two path components to a single preallocated character span, and returns a value that indicates whether the operation succeeded.

TryJoin(ReadOnlySpan<Char>, ReadOnlySpan<Char>, Span<Char>, Int32)

尝试将两个路径组件连接到一个预分配的字符范围,并返回一个值,该值指示操作是否成功。Attempts to concatenate two path components to a single preallocated character span, and returns a value that indicates whether the operation succeeded.

适用于

另请参阅