標籤:
1.管理檔案系統
一般而言,應用程式都會有儲存資料、檢索資料的需求。
1.1 使用 path 類來訪問檔案路徑
【path常用的方法】:http://www.cnblogs.com/tangge/archive/2012/10/30/2746458.html#a3
1.2 使用 File 和 FileInfo 類訪問檔案1.2.1 File 類
| 123456789101112131415161718 |
static void Main(string[] args){ string sourceFileName = @"F:\a.txt"; //源檔案 string destFileName = @"c:\a.txt"; //目標檔案 //如果源檔案不存在 if (!File.Exists(sourceFileName)) { File.Create(sourceFileName).Close(); } //如果目標檔案存在,先刪除 if (File.Exists(destFileName)) { File.Delete(destFileName); } File.Copy(sourceFileName, destFileName); File.Delete(sourceFileName);} |
重複記錄
string sourceFileName = @"F:\a.txt"; //源檔案 string destFileName = @"c:\a.txt"; //目標檔案 StreamWriter sw = File.AppendText(destFileName); sw.WriteLine(string.Format("{0}複製完畢", DateTime.Now)); sw.Flush(); sw.Close();
1.2.2 FileInfo 類
Length
private static void Main(string[] args) { string path = @"E:\中天IT\視頻\DVD-ASP.NET\DVD-張波.NETC1001\IO詳解——張波.NETC1001\1上次複習_作業講解.avi"; FileInfo fi = new FileInfo(path); Console.WriteLine( string.Format("本檔案為{0:#.00}M", fi.Length / (1024 * 1024))); }
1.3 使用Directory 和 DirectoryInfo 類訪問目錄1.3.1 Directory 類
string path = @"F:\tt\aeg\www"; if (Directory.Exists(path)) { Directory.Delete(path); } else { Directory.CreateDirectory(path); }
string path = @"F:\tt\aeg"; //GetFiles 檢索檔案清單 string[] aa= Directory.GetFiles(path); foreach (var a in aa) { Console.WriteLine(a); } Console.WriteLine("------------"); //GetDirectories 檢索資料夾清單 foreach (var s in Directory.GetDirectories(path)) { Console.WriteLine(s); } Console.WriteLine("------------"); //GetDirectories 檢索檔案夾和檔案清單 foreach (var s in Directory.GetFileSystemEntries(path)) { Console.WriteLine(s); }
1.3.2 DirectoryInfo 類
1.4 使用 DriveInfo 類訪問磁碟機
Console.WriteLine("磁碟機{0},類型為{1},",dr.Name,dr.DriveType); //if (dr.IsReady) //{ Console.WriteLine("可用空間為{0}", dr.AvailableFreeSpace); //}
Console.WriteLine("磁碟機{0},類型為{1},", dr.Name, dr.DriveType); if (dr.IsReady)//裝置已經準備好 { Console.WriteLine("\t可用空間為{0}G", dr.AvailableFreeSpace/(1024*1024*1024)); //41G Console.WriteLine("\t分區格式為{0}\n",dr.DriveFormat); //NTFS }
1.5 FileSystemWatcher 類
2.使用位元組流
3.管理應用程式資料
4.高效操作字串
(轉).NET的IO:Path、File、FileInfo、Directory、DirectoryInfo、DriveInfo、FileSystemWatcher