【.Net实用方法总结】 整理并总结System.IO中Path类及其方法介绍
🐋作者簡(jiǎn)介:博主是一位.Net開發(fā)者,同時(shí)也是RPA和低代碼平臺(tái)的踐行者。
🐬個(gè)人主頁:會(huì)敲鍵盤的肘子
🐰系列專欄:.Net實(shí)用方法總結(jié)
🦀專欄簡(jiǎn)介:博主針對(duì).Net開發(fā)和C站問答過程中遇到的問題進(jìn)行總結(jié),形成本專欄,希望可以幫助到您解決問題。
🐶座右銘:總有一天你所堅(jiān)持的會(huì)反過來擁抱你。
🌈寫在前面:
本文主要介紹System.IO命名空間的Path類,介紹其常用的方法和實(shí)踐。
👉本文關(guān)鍵字:System.IO、Path類、文件或目錄路徑信息、方法實(shí)踐、C#
文章目錄
- 1?? System.IO命名空間
- 2?? Path類
- ? 定義
- ? 常用方法
- ChangeExtension(String, String) 更改路徑字符串的擴(kuò)展名
- Combine(String[]) 將字符串?dāng)?shù)組組合成一個(gè)路徑
- GetFileName(String) 返回指定路徑字符串的文件名和擴(kuò)展名。
- GetFileNameWithoutExtension(String) 返回不具有擴(kuò)展名的指定路徑字符串的文件名
- GetFullPath(String) 返回指定路徑字符串的絕對(duì)路徑
- GetFullPath(String, String) 從完全限定的基路徑和相對(duì)路徑返回絕對(duì)路徑
- GetDirectoryName(String) 返回指定路徑的目錄信息
- GetExtension(String) 返回指定路徑字符串的擴(kuò)展名(包括句點(diǎn)“.”)
- GetPathRoot(String) 從指定字符串包含的路徑中獲取根目錄信息
- HasExtension(String) 確定路徑是否包括文件擴(kuò)展名
- IsPathRooted(String) 返回一個(gè)值,該值指示指定的路徑字符串是否包含根
- Join(String[]) 將路徑數(shù)組連接到一個(gè)路徑中
- ? 注解
- ? 更多方法
1?? System.IO命名空間
.NET中的IO操作命名空間,包含允許讀寫文件和數(shù)據(jù)流的類型以及提供基本文件和目錄支持的類型。
我們?cè)?NET中的IO操作,經(jīng)常需要調(diào)用一下幾個(gè)類。
- FileStream類
? 文件流類,負(fù)責(zé)大文件的拷貝,讀寫。
- Path類
? Path類中方法,基本都是對(duì)字符串(文件名)的操作,與實(shí)際文件沒多大關(guān)系。
-
File類
File類可以進(jìn)行一些對(duì)小文件拷貝、剪切操作,還能讀一些文檔文件。
-
Dirctory
目錄操作,創(chuàng)建文件、刪除目錄,獲取目錄下文件名等等。
2?? Path類
? 定義
對(duì)包含文件或目錄路徑信息的 String 實(shí)例執(zhí)行操作。 這些操作是以跨平臺(tái)的方式執(zhí)行的。
public static class Path? 常用方法
ChangeExtension(String, String) 更改路徑字符串的擴(kuò)展名
public static string? ChangeExtension (string? path, string? extension);參數(shù)
path
string
要修改的路徑信息。
string
extension
新的擴(kuò)展名(有或沒有前導(dǎo)句點(diǎn))。 指定 null 以從 path 移除現(xiàn)有擴(kuò)展名。
返回
已修改的路徑信息。
在基于 Windows 的桌面平臺(tái)上,如果 path 是 null 或空字符串 (“”),則返回的路徑信息是未修改的。 如果 extension 為 null,則返回的字符串包含指定的路徑(其擴(kuò)展名已移除)。 如果 path 不具有擴(kuò)展名且 extension 不為 null,則返回的路徑字符串包含追加到 path 結(jié)尾的 extension。
示例
public void ChangeExtension(){string goodFileName = @"C:\mydir\myfile.com.extension";string badFileName = @"C:\mydir\";string result;result = Path.ChangeExtension(goodFileName, ".old");Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'",goodFileName, result);result = Path.ChangeExtension(goodFileName, "");Console.WriteLine("ChangeExtension({0}, '') returns '{1}'",goodFileName, result);result = Path.ChangeExtension(badFileName, ".old");Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'",badFileName, result);// This code produces output similar to the following://// ChangeExtension(C:\mydir\myfile.com.extension, '.old') returns 'C:\mydir\myfile.com.old'// ChangeExtension(C:\mydir\myfile.com.extension, '') returns 'C:\mydir\myfile.com.'// ChangeExtension(C:\mydir\, '.old') returns 'C:\mydir\.old'}Combine(String[]) 將字符串?dāng)?shù)組組合成一個(gè)路徑
注:Combine(String, String)、Combine(String, String, String)、Combine(String, String, String, String)類似
public static string Combine (params string[] paths);參數(shù)
path
string[]
由路徑的各部分構(gòu)成的數(shù)組。
返回
string
已組合的路徑。
示例
string[] paths = {@"d:\archives", "2001", "media", "images"}; string fullPath = Path.Combine(paths); Console.WriteLine(fullPath);GetFileName(String) 返回指定路徑字符串的文件名和擴(kuò)展名。
public static string? GetFileName (string? path);參數(shù)
path
string
從中獲取文件名和擴(kuò)展名的路徑字符串。
返回
string
path 中最后的目錄分隔符后的字符。 如果 path 的最后一個(gè)字符是目錄或卷分隔符,則此方法返回 Empty。 如果 path 為 null,則此方法返回 null。
示例
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string result;result = Path.GetFileName(fileName); Console.WriteLine("GetFileName('{0}') returns '{1}'",fileName, result);result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') returns '{1}'",path, result);// This code produces output similar to the following: // // GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' // GetFileName('C:\mydir\') returns ''GetFileNameWithoutExtension(String) 返回不具有擴(kuò)展名的指定路徑字符串的文件名
public static string? GetFileNameWithoutExtension (string? path);參數(shù)
path
string
文件的路徑。
返回
string
path 中最后的目錄分隔符后的字符,不包括最后的句點(diǎn) (.) 以及之后的所有字符。
示例
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string result;result = Path.GetFileNameWithoutExtension(fileName); Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'",fileName, result);result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') returns '{1}'",path, result);// This code produces output similar to the following: // // GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile' // GetFileName('C:\mydir\') returns ''GetFullPath(String) 返回指定路徑字符串的絕對(duì)路徑
public static string GetFullPath (string path);參數(shù)
path
string
要獲取其絕對(duì)路徑信息的文件或目錄。
返回
string
完全限定的位置 path,例如“C:\MyFile.txt”。
示例
string fileName = "myfile.ext"; string path1 = @"mydir"; string path2 = @"\mydir"; string fullPath;fullPath = Path.GetFullPath(path1); Console.WriteLine("GetFullPath('{0}') returns '{1}'",path1, fullPath);fullPath = Path.GetFullPath(fileName); Console.WriteLine("GetFullPath('{0}') returns '{1}'",fileName, fullPath);fullPath = Path.GetFullPath(path2); Console.WriteLine("GetFullPath('{0}') returns '{1}'",path2, fullPath);// Output is based on your current directory, except // in the last case, where it is based on the root drive // GetFullPath('mydir') returns 'C:\temp\Demo\mydir' // GetFullPath('myfile.ext') returns 'C:\temp\Demo\myfile.ext' // GetFullPath('\mydir') returns 'C:\mydir'補(bǔ)充
如果 path 為相對(duì)路徑,此重載將返回完全限定的路徑,該路徑可以基于當(dāng)前驅(qū)動(dòng)器和當(dāng)前目錄。 應(yīng)用程序執(zhí)行時(shí),當(dāng)前驅(qū)動(dòng)器和當(dāng)前目錄可以隨時(shí)更改。 因此,無法提前確定此重載返回的路徑。 若要返回確定性路徑,請(qǐng)調(diào)用 GetFullPath(String, String) 重載。 還可以調(diào)用 IsPathFullyQualified 該方法來確定路徑是完全限定還是相對(duì)路徑,因此是否需要調(diào)用 GetFullPath 。
GetFullPath(String, String) 從完全限定的基路徑和相對(duì)路徑返回絕對(duì)路徑
public static string GetFullPath (string path, string basePath);參數(shù)
path
string
連接到 basePath 的相對(duì)路徑。
basePath
string
完全限定路徑的開頭。
返回
string
絕對(duì)路徑。
示例
using System; using System.IO;class Program {static void Main(){string basePath = Environment.CurrentDirectory;string relativePath = "./data/output.xml";// Unexpectedly change the current directory.Environment.CurrentDirectory = "C:/Users/Public/Documents/";string fullPath = Path.GetFullPath(relativePath, basePath);Console.WriteLine($"Current directory:\n {Environment.CurrentDirectory}");Console.WriteLine($"Fully qualified path:\n {fullPath}");} } // The example displays the following output: // Current directory: // C:\Users\Public\Documents // Fully qualified path: // C:\Utilities\data\output.xmlGetDirectoryName(String) 返回指定路徑的目錄信息
public static string? GetDirectoryName (string? path);參數(shù)
path
string
文件或目錄的路徑。
返回
string
path 的目錄信息;如果 path 表示根目錄或?yàn)?null,則為 null。 如果 path 不包含目錄信息,則返回 Empty。
示例
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 '' */GetExtension(String) 返回指定路徑字符串的擴(kuò)展名(包括句點(diǎn)“.”)
public static string? GetExtension (string? path);參數(shù)
path
string
從中獲取擴(kuò)展名的路徑字符串。
返回
string
指定路徑的擴(kuò)展名(包含句點(diǎn)“.”)、或 null、或 Empty。 如果 path 為 null,則 GetExtension(String) 返回 null。 如果 path 不具有擴(kuò)展名信息,則 GetExtension(String) 返回 Empty。
示例
string fileName = @"C:\mydir.old\myfile.ext"; string path = @"C:\mydir.old\"; string extension;extension = Path.GetExtension(fileName); Console.WriteLine("GetExtension('{0}') returns '{1}'",fileName, extension);extension = Path.GetExtension(path); Console.WriteLine("GetExtension('{0}') returns '{1}'",path, extension);// This code produces output similar to the following: // // GetExtension('C:\mydir.old\myfile.ext') returns '.ext' // GetExtension('C:\mydir.old\') returns ''GetPathRoot(String) 從指定字符串包含的路徑中獲取根目錄信息
public static string? GetPathRoot (string? path);參數(shù)
path
string
一個(gè)字符串,包含要從中獲取根目錄信息的路徑。
返回
string
如果為根路徑,則為 path 的根目錄。
- 或 - 如果 path 不包含根目錄信息,則為 Empty。
- 或 - 如果 path 為 null 或?qū)嶋H上為空,則為 null。
示例
string path = @"\mydir\"; string fileName = "myfile.ext"; string fullPath = @"C:\mydir\myfile.ext"; string pathRoot;pathRoot = Path.GetPathRoot(path); Console.WriteLine("GetPathRoot('{0}') returns '{1}'",path, pathRoot);pathRoot = Path.GetPathRoot(fileName); Console.WriteLine("GetPathRoot('{0}') returns '{1}'",fileName, pathRoot);pathRoot = Path.GetPathRoot(fullPath); Console.WriteLine("GetPathRoot('{0}') returns '{1}'",fullPath, pathRoot);// This code produces output similar to the following: // // GetPathRoot('\mydir\') returns '\' // GetPathRoot('myfile.ext') returns '' // GetPathRoot('C:\mydir\myfile.ext') returns 'C:\'string fileName = @"C:\mydir.old\myfile.ext"; string path = @"C:\mydir.old\"; string extension;extension = Path.GetExtension(fileName); Console.WriteLine("GetExtension('{0}') returns '{1}'",fileName, extension);extension = Path.GetExtension(path); Console.WriteLine("GetExtension('{0}') returns '{1}'",path, extension);// This code produces output similar to the following: // // GetExtension('C:\mydir.old\myfile.ext') returns '.ext' // GetExtension('C:\mydir.old\') returns ''HasExtension(String) 確定路徑是否包括文件擴(kuò)展名
public static bool HasExtension (string? path);參數(shù)
path
string
用于搜索擴(kuò)展名的路徑。
返回
bool
true 如果路徑中最后一個(gè)目錄分隔符后面的字符 (\ 或 /) 或卷分隔符 (:) 包含句點(diǎn) (.) 后跟一個(gè)或多個(gè)字符,則為 ;否則為 false。
示例
string fileName1 = "myfile.ext"; string fileName2 = @"mydir\myfile"; string path = @"C:\mydir.ext\"; bool result;result = Path.HasExtension(fileName1); Console.WriteLine("HasExtension('{0}') returns {1}",fileName1, result);result = Path.HasExtension(fileName2); Console.WriteLine("HasExtension('{0}') returns {1}",fileName2, result);result = Path.HasExtension(path); Console.WriteLine("HasExtension('{0}') returns {1}",path, result);// This code produces output similar to the following: // // HasExtension('myfile.ext') returns True // HasExtension('mydir\myfile') returns False // HasExtension('C:\mydir.ext\') returns FalseIsPathRooted(String) 返回一個(gè)值,該值指示指定的路徑字符串是否包含根
public static bool IsPathRooted (string? path);參數(shù)
path
string
要測(cè)試的路徑。
返回
bool
如果 path 包含一個(gè)根,則為 true;否則為 false。
示例
string fileName = @"C:\mydir\myfile.ext"; string UncPath = @"\\myPc\mydir\myfile"; string relativePath = @"mydir\sudir\"; bool result;result = Path.IsPathRooted(fileName); Console.WriteLine("IsPathRooted('{0}') returns {1}",fileName, result);result = Path.IsPathRooted(UncPath); Console.WriteLine("IsPathRooted('{0}') returns {1}",UncPath, result);result = Path.IsPathRooted(relativePath); Console.WriteLine("IsPathRooted('{0}') returns {1}",relativePath, result);// This code produces output similar to the following: // // IsPathRooted('C:\mydir\myfile.ext') returns True // IsPathRooted('\\myPc\mydir\myfile') returns True // IsPathRooted('mydir\sudir\') returns FalseJoin(String[]) 將路徑數(shù)組連接到一個(gè)路徑中
public static bool IsPathRooted (string? path);參數(shù)
path
string[]
路徑的數(shù)組。
返回
bool
連接的路徑。
補(bǔ)充
Combine與該方法不同,該方法Join不會(huì)嘗試對(duì)返回的路徑進(jìn)行根目錄。 (也就是說,如果除最后一個(gè)路徑之外的任何路徑 paths是絕對(duì)路徑,該方法 Join 不會(huì)像該方法那樣 Combine 放棄以前的路徑。
示例
using System; using System.IO;class Program2 {static void Main(){var path1 = "C:/Program Files/";var path2 = "Utilities/SystemUtilities";ShowPathInformation(path1, path2);path1 = "C:/";path2 = "/Program Files";ShowPathInformation(path1, path2);path1 = "C:/Users/Public/Documents/";path2 = "C:/Users/User1/Documents/Financial/";ShowPathInformation(path1, path2);}private static void ShowPathInformation(string path1, string path2){var result = Path.Join(path1.AsSpan(), path2.AsSpan());Console.WriteLine($"Concatenating '{path1}' and '{path2}'");Console.WriteLine($" Path.Join: '{result}'");Console.WriteLine($" Path.Combine: '{Path.Combine(path1, path2)}'");} } // The example displays the following output if run on a Windows system: // Concatenating 'C:/Program Files/' and 'Utilities/SystemUtilities' // Path.Join: 'C:/Program Files/Utilities/SystemUtilities' // Path.Combine: 'C:/Program Files/Utilities/SystemUtilities' // // Concatenating 'C:/' and '/Program Files' // Path.Join: 'C://Program Files' // Path.Combine: '/Program Files' // // Concatenating 'C:/Users/Public/Documents/' and 'C:/Users/User1/Documents/Financial/' // Path.Join: 'C:/Users/Public/Documents/C:/Users/User1/Documents/Financial/' // Path.Combine: 'C:/Users/User1/Documents/Financial/'? 注解
路徑是提供文件或目錄位置的字符串。路徑可以包含絕對(duì)或相對(duì)位置信息。 絕對(duì)路徑完全指定位置:無論當(dāng)前位置如何,都可以唯一標(biāo)識(shí)文件或目錄。 相對(duì)路徑指定部分位置:定位使用相對(duì)路徑指定的文件時(shí),當(dāng)前位置用作起點(diǎn)。
類的 Path 大多數(shù)成員不會(huì)與文件系統(tǒng)交互,并且不驗(yàn)證路徑字符串指定的文件是否存在。 Path 修改路徑字符串的類成員(例如 ChangeExtension)對(duì)文件系統(tǒng)中的文件名稱沒有影響。
類的成員 Path 使你可以快速輕松地執(zhí)行常見操作,例如確定文件擴(kuò)展名是否是路徑的一部分,并將兩個(gè)字符串組合成一個(gè)路徑名稱。
類的所有成員都是靜態(tài)的 Path ,因此無需路徑實(shí)例即可調(diào)用。
備注
在接受路徑作為輸入字符串的成員中,該路徑的格式必須良好或引發(fā)異常。 例如,如果路徑完全限定,但以空格開頭,則路徑不會(huì)在類的方法中修整。 因此,路徑格式不正確,并引發(fā)異常。 同樣,路徑或路徑的組合不能完全限定兩次。 例如,“c:temp c:\windows”在大多數(shù)情況下也會(huì)引發(fā)異常。 使用接受路徑字符串的方法時(shí),請(qǐng)確保路徑格式良好。
? 更多方法
更多方法請(qǐng)查閱官方文檔Path類。
?寫在結(jié)尾:
文章中出現(xiàn)的任何錯(cuò)誤請(qǐng)大家批評(píng)指出,一定及時(shí)修改。
希望寫在這里的小伙伴能給個(gè)三連支持!
總結(jié)
以上是生活随笔為你收集整理的【.Net实用方法总结】 整理并总结System.IO中Path类及其方法介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 神仙打架!清华公布2020特奖候选人名单
- 下一篇: TCP/UDP 协议格式