C#
本隨筆為個人復習鞏固知識用,多從書上總結與理解歸納得來,如有錯誤麻煩指正
I/O操作主要針對計算機檔案的創建和修改,基本包括創建檔案、讀寫檔案和洗掉檔案,
1.寫檔案
寫檔案即是將資料存入到一個檔案的程序,
static void Main(string[] args) { //存盤檔案的路徑和檔案名 string file = "d://test.dat"; string[] data = https://www.cnblogs.com/zzuadj/archive/2020/12/08/new string[2]; data[0] = "第一條資訊"; data[1] = "第二條資訊"; //將上述資訊寫入對應檔案 System.IO.File.WriteAllLines(file, data); Console.ReadKey();//按任意鍵退出 }

打開d盤就能看到程式創建的檔案了(越發覺得我手上的書不夠嚴謹,書上參考示例寫的是d盤,注釋時候卻說了c盤),用文本編輯器比如記事本方式打開就能看到置入的資訊了,
2.讀檔案
讀取檔案時需要參考寫檔案的程序,按照寫檔案時候的文本格式將資料讀出來,要注意的是先用Exists判斷是否存在對應檔案,然后將資料讀入到string陣列中,最后在控制臺上顯示,
//存盤檔案的路徑和檔案名 string file = "d://test.dat"; if (System.IO.File.Exists(file)) { String[] data = new string[2];//存盤讀入的資料 data = https://www.cnblogs.com/zzuadj/archive/2020/12/08/System.IO.File.ReadAllLines(file);//將d盤中的test.dat讀出 //列印資料 Console.WriteLine(data[0]); Console.WriteLine(data[1]); } Console.ReadKey();//按任意鍵退出

3.洗掉檔案
//存盤檔案的路徑和檔案名 string file = "d://test.dat"; if (System.IO.File.Exists(file)) { System.IO.File.Delete(file); }
4.二進制讀寫
任何資料型別都可以將其轉換為byte存入到陣列中,然后寫入到檔案中,讀取回來時再轉為正確的資料型別來使用,
string file = "d:\\test.dat";//存盤檔案的路徑和檔案名 //需要存盤的資料 int data1 = 100; float data2 = 0.1f; FileStream fs = new FileStream(file, FileMode.Create); //創建新檔案 BinaryWriter bw = new BinaryWriter(fs); //二進制寫入器 bw.Write(data1); bw.Write(data2); //將資料寫入檔案中 bw.Close(); fs.Close(); //注意關閉檔案 fs = new FileStream(file, FileMode.Open);//讀取檔案 BinaryReader br = new BinaryReader(fs);//二進制讀取器 int readInt = br.ReadInt32();//注意讀的順序要和寫的一致 float readFloat = br.ReadSingle(); br.Close(); fs.Close(); Console.WriteLine("{0},{1}", readInt, readFloat);//列印資料 Console.ReadKey();//按任意鍵退出
書中重點強調了IO操作在程式開發中的重點地位,列出了最常用的幾個類,分別是FileSteam(檔案流)、fileInfo、file(功能近似fileInfo,但全部靜態實作)、DirectoryInfo,Directory(功能和Directory類似,但全部靜態實作)、path(處理路徑名稱)等,
之后會另開篇章講述,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/231683.html
標籤:.NET技术
上一篇:F# 函式式編程之 - 一個例子
