C# 檔案操作相關知識
阿新 • • 發佈:2020-11-18
1.File類和FileInfo類
主要主要提供有關檔案的各種操作,比如建立、複製、移動、刪除、開啟檔案等操作。用於協助建立FileStream物件 1、File是靜態方法、FileInfo是動態方法,需要例項化
File類的常用方法
//判斷檔案是否存在 File.Exists(path); //建立檔案 FileStream fs = File.Create(path); //開啟檔案 第二個引數為列舉值 FileStream fs = File.Open(path,FileMode.Create); //複製檔案 File.Copy(old_path, new_path); //移動檔案 File.Move(old_path, new_path);//刪除檔案 File.Delete(path); /* FileMode的六種列舉值 FileMode.Append 開啟現有檔案並定位至檔案結尾,或建立新檔案 FileMode.Create 建立檔案,如果存在將會被改寫 FileMode.CreateNew 建立新檔案,如果檔案存在將會引發異常 FileMode.Open 開啟現有檔案 FileMode.OpenOrCreat 如果檔案存在,開啟;如果不存在,建立檔案 FileMode.Truncate 開啟現有檔案,檔案一旦被開啟,將被截斷為0位元組 */
FileInfo類常用方法
//例項化FileInfoFileInfo fileInfo = new FileInfo(path); //FileInfo類的屬性 //判斷檔案是否存在 bool idEx= fileInfo.Exists; //提取檔案的副檔名 string name = fileInfo.Extension; //獲取檔案的完整路徑 string fullPath = fileInfo.FullName; //獲取或設定上一次檔案的訪問時間 DateTime getTime = fileInfo.LastAccessTime; //獲取上一次修改檔案的時間 DateTime setTime = fileInfo.LastWriteTime; //獲取檔案建立時間DateTime creamTime = fileInfo.CreationTime; //獲取包含當前檔案的資料夾資訊物件 DirectoryInfo directoryInfo = fileInfo.Directory; //獲取包含檔案目錄的資料夾路徑 string directory = fileInfo.DirectoryName; //獲取檔案大小 以位元組為單位 long bit= fileInfo.Length;
2.Directory類和DirectoryInfo類
string path = ""; //判斷資料夾是否存在 bool idExists = Directory.Exists(path); //建立資料夾,返回資料夾建立資訊 DirectoryInfo dirInfo = Directory.CreateDirectory(path); //刪除資料夾 Directory.Delete(path); //移動資料夾 Directory.Move(old_path, new_path); //獲取資料夾下所有檔案 string[] filesPath = Directory.GetFiles(path); //獲取資料夾下所有資料夾 string[] directorysPath = Directory.GetDirectories(path);