System.IO.Path.GetDirectoryName 方法

方法描述

返回指定路径字符串的目录信息。

语法定义(C# System.IO.Path.GetDirectoryName 方法 的用法)

public static string GetDirectoryName(
	string path
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 文件或目录的路径。
返回值 System.String path 的目录信息,如果 path 表示根目录或为 null,则该目录信息为 null。 如果 path 没有包含目录信息,则返回 String.Empty。

提示和注释

大多数情况下,此方法返回的字符串由路径中最后的 DirectorySeparatorChar 或 AltDirectorySeparatorChar 之前(不包括该字符)的所有字符组成。 如果路径由根目录组成,如“c:\”,则返回 null。 注意此方法不支持使用“file:”的路径。 由于返回的路径不包含 DirectorySeparatorChar 或 AltDirectorySeparatorChar,因此将返回的路径传回 GetDirectoryName 方法会导致随后每次调用得到的字符串时截断一个文件夹级别。 例如,将路径“C:\Directory\SubDirectory\test.txt”传入 GetDirectoryName 方法将返回“C:\Directory\SubDirectory”。 将该字符串“C:\Directory\SubDirectory”传入 GetDirectoryName 将导致返回“C:\Directory”。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.Path.GetDirectoryName 方法例子

下面的代码示例演示如何在基于 Windows 的桌面平台上使用 GetDirectoryName 方法。

string filePath = @"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;

while (filePath != null)
{
    directoryName = Path.GetDirectoryName(filePath);
    Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
        filePath, directoryName);
    filePath = directoryName;
    if (i == 1)
    {
        filePath = directoryName + @"\";  // this will preserve the previous path
    }
    i++;
}
/*
This code produces the following output:

GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns ''
*/

异常

异常 异常描述
ArgumentException path 参数包含无效字符、为空、或仅包含空白。
PathTooLongException path 参数的长度超过系统定义的最大长度。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。