C#路径教程展示了如何在C#中使用文件和目录路径信息。这些操作以跨平台的方式执行。C#教程是C#语言的综合教程。
Path
位于System.IO
命名空间中。通过Path
类,我们可以轻松找出根路径,即目录文件名、扩展名或创建一个随机文件名。
C#路径.GetPathRoot
Path.GetPathRoot
方法从指定字符范围内包含的路径返回根目录信息。
var path = "/home/janbodnar/tmp/"; var root = Path.GetPathRoot(path); Console.WriteLine(root);
该示例打印指定路径的根路径。
$ dotnet run /
C#路径.GetDirectoryName
Path.GetDirectoryName
返回由字符范围表示的指定路径的目录信息。
var path = "/home/janbodnar/words.txt"; var dirName = Path.GetDirectoryName(path); Console.WriteLine(dirName);
该示例打印指定路径的目录名称。
$ dotnet run /home/janbodnar
C#路径.GetFullPath
Path.GetFullPath
返回指定路径字符串的绝对路径。
var path = "."; var fullPath = Path.GetFullPath(path); Console.WriteLine(fullPath);
该示例打印当前工作目录的完整路径。
$ dotnet run /home/janbodnar/Documents/prog/c#/path/FullPath
C#路径.GetRandomFileName
Path.GetRandomFileName
返回一个随机目录或文件名。
var randFileName = Path.GetRandomFileName(); Console.WriteLine(randFileName); Console.WriteLine(Path.GetTempPath());
该示例打印随机生成的文件名的示例。
$ dotnet run j1wtvfxj.zrh
C#路径文件名和扩展名
Path.GetExtension
返回指定路径字符串的扩展名(包括句点)。Path.GetFileName
返回由只读字符范围表示的文件路径的文件名和扩展名。Path.GetFileNameWithoutExtension
返回没有文件路径扩展名的文件名由只读字符范围表示。
var path = "/home/janbodnar/words.txt"; var fileExt = Path.GetExtension(path); Console.WriteLine(fileExt); var fileName = Path.GetFileName(path); Console.WriteLine(fileName); var fileNameWithoutExt = Path.GetFileNameWithoutExtension(path); Console.WriteLine(fileNameWithoutExt);
该示例打印指定路径的扩展名、文件名和不带扩展名的文件名。
$ dotnet run .txt words.txt words
C#Path.Combine
Path.Combine
将字符串组合成一个路径。
var fullPath1 = Path.Combine("/home", "janbodnar", "words.txt"); Console.WriteLine(fullPath1); var fullPath2 = Path.Combine("/home/janbodnar/", "/home/janbodnar/words2.txt"); Console.WriteLine(fullPath2);
该示例将单个字符串连接成表示文件路径的单个字符串。
$ dotnet run /home/janbodnar/words.txt /home/janbodnar/words2.txt
在本文中,我们使用了C#中的路径字符串。
列出所有C#教程。