.net 6 C#中System.IO.Path类的用法

1. 说明

/*
Performs operations on System.String instances that contain file 
or directory path information. 
These operations are performed in a cross-platform manner.

对系统执行操作。包含文件或目录的字符串实例路径信息。
这些操作是以跨平台的方式执行的。
*/

2. 属性

2.1 AltDirectorySeparatorChar

/*
Provides a platform-specific alternate character 
used to separate directory levels
in a path string that reflects a hierarchical file system organization.

提供用于分隔目录级别的特定于平台的备用字符
在反映分层文件系统组织的路径字符串中。
*/
Console.WriteLine(Path.AltDirectorySeparatorChar); 
// 输出结果:/

2.2 DirectorySeparatorChar

/*
Provides a platform-specific character 
used to separate directory levels in a
path string that reflects a hierarchical file system organization.

提供一个特定于平台的字符,
用于在中分隔目录级别反映分层文件系统组织的路径字符串。
*/
Console.WriteLine(Path.DirectorySeparatorChar); 
// 输出结果:\

2.3 VolumeSeparatorChar

/*
Provides a platform-specific volume separator character.

提供特定于平台的卷分隔符字符。
*/
Console.WriteLine(Path.VolumeSeparatorChar); 
// 输出结果::

3. 方法

3.1 GetFileName

var file= "D:\\data\\files\\测试文件.pdf";
 Console.WriteLine(Path.GetFileName(file));
// 输出结果:测试文件.pdf

3.2 GetFileNameWithoutExtension

var file= "D:\\data\\files\\测试文件.pdf";
 Console.WriteLine(Path.GetFileNameWithoutExtension(file));
// 输出结果:测试文件

3.3 GetDirectoryName

var file= "D:\\data\\files\\测试文件.pdf";
 Console.WriteLine(Path.GetDirectoryName(file));
// 输出结果:D:\\data\\files

3.4 GetExtension

var file= "D:\\data\\files\\测试文件.pdf";
 Console.WriteLine(Path.GetExtension(file));
// 输出结果:.pdf

3.5 GetFullPath

var file= "D:\\data\\files\\测试文件.pdf";
 Console.WriteLine(Path.GetFullPath(file));
// 输出结果:D:\\data\\files\\测试文件.pdf

3.6 GetRelativePath

 var basePath = @"C:\Users\Example\Documents";
 var targetPath = @"C:\Users\Example\Documents\Projects\ExampleProject";

 Console.WriteLine(Path.GetRelativePath(basePath, targetPath));

// 输出结果:Projects\ExampleProject

3.7 GetTempFileName


// 在磁盘上创建一个唯一命名的零字节大小的临时文件,
并返回完整的该文件的路径。

Console.WriteLine(Path.GetTempFileName());

// 输出结果:C:\Users\xxx\AppData\Local\Temp\tmpD10E.tmp

3.8 GetTempPath


// 返回当前用户的临时文件夹的路径。

Console.WriteLine(Path.GetTempPath());

// 输出结果:C:\Users\xxx\AppData\Local\Temp\

3.9 GetPathRoot


// 从指定字符串中包含的路径获取根目录信息。

var file= "D:\\data\\files\\测试文件.pdf";
Console.WriteLine(Path.GetPathRoot());

// 输出结果:D:\

3.10 GetRandomFileName


// 返回随机的文件夹名或文件名。。

Console.WriteLine(Path.GetRandomFileName());

// 输出结果:a54n1pir.yw3

3.11 ChangeExtension


// 修改扩展名。
var file= "D:\\data\\files\\测试文件.pdf";

Console.WriteLine(Path.ChangeExtension(file, ".docx"));

// 输出结果:D:\data\files\测试文件.docx
posted @ 2024-04-18 11:37  鸑鷟虽孤  阅读(126)  评论(2编辑  收藏  举报