檔案路徑截取內容
在檔案的讀取、保存操作時可能需要對路徑執行裁剪、拼接,比如獲取一個text檔案的目錄位置,回傳指定字串的檔案名和擴展名,確定路徑是否包含檔案夾擴展名等等,而我們自己寫的方法很多時候,在多語言處理或者截取字串長度時容易出現問題,這篇主要是梳理System.IO.Path命名空間下提供的函式能實作對應的哪些功能,通過這些函式我們不需要自己在去寫對應的截取路徑代碼,
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string filePath = @"d:\duwenlong\test\path.txt";
FilePathTextBox.Text += $"檔案路徑: {filePath}\r\n";
FilePathTextBox.Text += $"更改路徑字串的擴展名: \r\n";
FilePathTextBox.Text += System.IO.Path.ChangeExtension(filePath, "zip") + "\r\n";
FilePathTextBox.Text += $"回傳指定路徑字串的目錄資訊: {filePath}\r\n";
FilePathTextBox.Text += System.IO.Path.GetDirectoryName(filePath) + "\r\n";
FilePathTextBox.Text += "回傳指定的路徑字串的擴展名,\r\n";
FilePathTextBox.Text += System.IO.Path.GetExtension(filePath) + "\r\n";
FilePathTextBox.Text += "回傳指定路徑字串的檔案名和擴展名,\r\n";
FilePathTextBox.Text += System.IO.Path.GetFileName(filePath) + "\r\n";
FilePathTextBox.Text += "回傳不具有擴展名的指定路徑字串的檔案名,\r\n";
FilePathTextBox.Text += System.IO.Path.GetFileNameWithoutExtension(filePath) + "\r\n";
FilePathTextBox.Text += "獲取指定路徑的根目錄資訊,\r\n";
FilePathTextBox.Text += System.IO.Path.GetPathRoot(filePath) + "\r\n";
FilePathTextBox.Text += "回傳隨機檔案夾名或檔案名,\r\n";
FilePathTextBox.Text += System.IO.Path.GetRandomFileName() + "\r\n";
FilePathTextBox.Text += "創建磁盤上唯一命名的零位元組的臨時檔案并回傳該檔案的完整路徑,\r\n";
FilePathTextBox.Text += System.IO.Path.GetTempFileName() + "\r\n";
FilePathTextBox.Text += "回傳當前系統的臨時檔案夾的路徑,\r\n";
FilePathTextBox.Text += System.IO.Path.GetTempPath() + "\r\n";
FilePathTextBox.Text += "確定路徑是否包括檔案擴展名,\r\n";
FilePathTextBox.Text += System.IO.Path.HasExtension(filePath) + "\r\n";
FilePathTextBox.Text += "獲取一個值,該值指示指定的路徑字串是包含絕對路徑資訊還是包含相對路徑資訊,\r\n";
FilePathTextBox.Text += System.IO.Path.IsPathRooted(filePath) + "\r\n";
}
一般作業時從路徑字串中獲取需要對應的資訊,使用上面的API就可以拿到想要的東西,自己拼接或拆分路徑時,可能會遇到并且需要處理多語言編碼的編碼問題、路徑中包含不同語言奇怪字符的問題,和不同語言下,和,互換的問題等等,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/287512.html
標籤:C#
