Path.GetDirectoryName()
方法是C#中的一个用于操作文件路径的静态方法,可用于获取文件路径的目录部分,即去除文件名的部分。
它以字符串形式返回路径中的目录信息,如果路径是空的,或者只包含根目录,则返回null。
以下是使用该方法的示例:
- 获取文件所在目录
string filePath = "C:/Users/Admin/Desktop/sample.txt";
string directoryPath = Path.GetDirectoryName(filePath);
Console.WriteLine(directoryPath);
//输出:C:/Users/Admin/Desktop
- 从相对路径中获取目录
string relativePath = "../images/avatar.jpg";
string absolutePath = Path.GetFullPath(relativePath);
string directoryPath = Path.GetDirectoryName(absolutePath);
Console.WriteLine(directoryPath);
//输出:C:/Users/Admin/Desktop/images
在此实例中,我们首先使用Path.GetFullPath
方法将相对路径转换为绝对路径。然后,我们使用Path.GetDirectoryName
方法从绝对路径中获取目录信息。
注意,Path.GetDirectoryName
方法只能用于文件路径,不能用于URL路径。
综上所述,Path.GetDirectoryName()
方法是一个常用的工具方法,用于获取文件路径的目录部分,并在许多应用程序中都得到广泛的应用。