標籤:
Path 類:路徑類
path.GetFileName("檔案路徑")//擷取完整檔案名稱,包括檔案名稱和檔案拓展名
Path.GetFileNameWithoutExtension("檔案路徑")//擷取檔案名稱,不包括拓展名
Path.GetExtension("檔案路徑")//擷取檔案名稱的拓展名
Path.GetDirectoryName("檔案路徑")//返回指定檔案路徑的字串資訊,即檔案所在的檔案夾的路徑名稱
Path.GetFullPath("檔案路徑")//獲得檔案所在的檔案夾的全路徑,包括檔案夾名和完整檔案名稱
Path.Combine("檔案路徑")//合并路徑
File 類:檔案類。用於操作檔案,可進行一次性讀寫檔案。
.Create("檔案路徑")//建立一個檔案
.Delete("檔案路徑")//刪除一個檔案(永久刪除,檔案不存在也不發異常)
File.ReadAllBytes("開啟檔案路徑")//開啟一個路徑下的檔案,將檔案的內容讀入一個字串,然後關閉該檔案,返回一個位元組數組
File.WriteAllBytes("建立檔案路徑",位元組數組)//建立一個新檔案,在其中寫入指定的位元組數組,然後關閉該檔案。如果目標檔案已存在,則覆蓋該檔案。
Encoding 類:字元編碼類
Encoding.Default//擷取系統當前SNSI字碼頁的編碼
Encoding.Default.GetString()//將指定位元組數組中的所有位元組解碼為一個字串,返回一個字串
Encoding.Default.GetBytes()//將指定字串中的所有字元編碼為一個位元組數組,返回一個位元組數組
FileStream 類:檔案流類。
.Read()//從流中讀取位元組塊並將該資料寫入給定緩衝區中。返回一個int值,表示讀入緩衝區中的總位元組數,為0表示已到達流的末尾,讀取完畢。
.Write()//使用從緩衝區讀取的資料將位元組塊寫入該流。沒有傳回值。
.Close()//
.Dispose()//
Read()方法例子:
1 string path = @"D:\file.txt"; 2 FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read); 3 byte[] buffer = new byte[1024 * 1024 * 5];//5mb的大小 4 //返回本次實際讀取的有效位元組數 5 int r = fsRead.Read(buffer, 0, buffer.Length); 6 //將位元組數組中每個元素按指定的編碼格式解碼成字串 7 string str = Encoding.Default.GetString(buffer, 0, r); 8 //關閉流 9 fsRead.Close();10 //釋放流所佔用資源11 fsRead.Dispose();12 Console.WriteLine(str);
View Code
Write()方法例子:
1 string str = @"D:\file.txt";2 using (FileStream fsWrite = new FileStream(str, FileMode.OpenOrCreate, FileAccess.Write))3 {4 string newstr = "寫入的內容!";5 byte[] buffer = Encoding.Default.GetBytes(newstr);6 fsWrite.Write(buffer, 0, buffer.Length);7 }View Code
複製一個多媒體檔案並存放到指定位置
1 /// <summary> 2 /// 複製一個多媒體檔案並存放到指定位置 3 /// </summary> 4 /// <param name="source">要複製多媒體檔案的路徑</param> 5 /// <param name="target">複製後的多媒體檔案存放的路徑</param> 6 public static void CopyFile(string source, string target) 7 { 8 //建立一個負責讀取的流 9 using (FileStream fsRead = new FileStream(source, FileMode.OpenOrCreate, FileAccess.Read))10 {11 //建立一個負責寫入的流12 using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))13 {14 byte[] buffer = new byte[1024 * 1024 * 5];15 while (true)16 {17 //讀取的位元組數18 int r = fsRead.Read(buffer, 0, buffer.Length);19 if (r == 0) { break; }20 fsWrite.Write(buffer, 0, r);21 }22 }23 }24 }View Code
StreamReader 類:從流中讀取字元
.ReadLine()//從當前流中讀取一行字元並將資料作為字串返回。
.EndOfStream//擷取一個值,該值表示當前的流位置是否在流的末尾。
例子:
1 string str = @"D:\file.txt";2 using (StreamReader sr = new StreamReader(str, Encoding.Default))3 {4 while (!sr.EndOfStream)5 {6 Console.WriteLine(sr.ReadLine());7 }8 }View Code
StreamWrite 類:以特定的編碼向流中寫入字元
常用建構函式: public StreamWriter(string path, bool append, Encoding encoding);//使用指定編碼和預設緩衝區大小,為指定路徑上的指定檔案初始化 System.IO.StreamWriter 類的新執行個體。如果該檔案存在,則可以將其覆蓋或向其追加。如果該檔案不存在,則此建構函式將建立一個新檔案。
.Write()//將字串寫入流。
.WriteLine()//將行結束符寫入文字資料流。
例子:
1 string str = @"D:\file.txt";2 using (StreamWriter sw = new StreamWriter(str, true, Encoding.Default))3 {4 sw.WriteLine();5 sw.Write("測試!");6 sw.WriteLine();7 sw.Write("123456");8 }View Code
C# 一些知識點總結(二)