c#簡單的檔案操作
FileInfo
使用FileInfo類的物件進行檔案進行外部操作:
FileInfo file = new FileInfo(@".\..\..\lzx.txt"); if (file.Exists) { Console.WriteLine("lzx.txt存在"); //file.Delete(); } else { Console.WriteLine("lzx.txt不存在"); file.Create(); }
這裡可以使用相對路徑和絕對路徑。需要注意是的當前路徑是位於工程檔案的.\bin\debug下的
FileInfo類下的方法都很好理解,自行檢視即可。
File
使用File對檔案內容進行操作。常用的三個讀寫方法:
寫:File.WriteAllText、File.WriteAllLines和File.WriteAllBytes
讀:File.ReadAllText、File.ReadAllLines和File.ReadAllBytes
寫段程式碼小跑下:
File.WriteAllText(@".\..\..\lzx1.txt", "hello world!"); string s1 = File.ReadAllText(@".\..\..\lzx1.txt"); Console.WriteLine(s1); string[] str = new string[]{"11","22","33","44"}; File.WriteAllLines(@".\..\..\lzx2.txt",str); string[] str2 = File.ReadAllLines(@".\..\..\lzx2.txt"); foreach (var temp in str2) { Console.WriteLine(temp); } byte[] data = File.ReadAllBytes(@".\..\..\頭像.jpg"); File.WriteAllBytes(@".\..\..\test.jpg",data); Console.ReadKey(); }
結果如下:
FileStream
一般使用FileStream處理二進位制檔案,如圖片。
直接上程式碼:
//FileStream readsStream = new FileStream(@".\..\..\lzx.txt",FileMode.Append); FileStream readsStream = new FileStream(@".\..\..\頭像.jpg",FileMode.Open); FileStream writeStream = new FileStream(@".\..\..\頭像備份.jpg",FileMode.OpenOrCreate); byte[] data = new byte[1024]; while (true) { int length = readsStream.Read(data, 0, 1024);//每次返回讀取的位元組數,若讀取完畢則返回0 writeStream.Write(data, 0, length); Console.WriteLine(length); if (length==0) { break; } } //一定要關閉檔案流,不然會出現寫入資料不完整的情況 readsStream.Close(); writeStream.Close(); Console.ReadKey();
在工程資料夾下開啟(不存在就建立新的)檔案”頭像備份.jpg”並將”頭像.jpg”檔案的內容複製到其中。
檔案流處理分為好幾種情況。一般來說獨佔檔案開啟的話,如果不關閉檔案流,那麼其它程序就無法讀取這個檔案了。二在使用寫入模式開啟檔案的時候,如果不進行close可能會有部分資料在快取中沒有真實寫入檔案中,這樣其它程式開啟檔案時看到的資料就不完整了。
所以使用後一定要關閉檔案流,不然會出現寫入檔案不完整的情況。比如:
如果需要進行大檔案的複製,可以參考這篇部落格:https://www.cnblogs.com/wolf-sun/p/3345392.html
StreamReader和StreamWriter
使用StreamReader和StreamWriter來讀寫文字檔案。十分簡易:
StreamReader reader = new StreamReader(@".\..\..\lzx.txt");//不存在則丟擲異常 StreamWriter writer = new StreamWriter(@".\..\..\test.txt");//存在就開啟並覆蓋,沒有則建立 //寫入 while (true) { string message = Console.ReadLine(); if (message =="q") break; //writer.Write(message);//寫成一串 writer.WriteLine(message);//寫成一行 } //讀取 while (true) { string message = reader.ReadLine(); if (message==null) break; Console.WriteLine(message); } reader.Close(); writer.Close(); Console.ReadKey();
很好理解。
資料夾操作
與檔案操作類似,使用DirectoryInfo類的物件進行檔案操作:
DirectoryInfo dirInfo = newDirectoryInfo(".");
Console.WriteLine(dirInfo.FullName);
獲取資料夾的完整路徑,其他方法也很簡單,這裡也不過多演示。