標籤:asp void directory 判斷 方法 獲得 and 封裝 ram
轉自:https://www.cnblogs.com/wangshenhe/archive/2012/05/09/2490438.html
檔案與檔案夾操作主要用到以下幾個類:
1.File類:
提供用於建立、複製、刪除、移動和開啟檔案的靜態方法,並協助建立 FileStream 對象。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file(v=VS.80).aspx
2.FileInfo類:
提供建立、複製、刪除、移動和開啟檔案的執行個體方法,並且協助建立 FileStream 對象
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.fileinfo(v=VS.80).aspx
3.Directory類:
公開用於建立、移動和枚舉通過目錄和子目錄的靜態方法。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directory.aspx
4.DirectoryInfo類:
公開用於建立、移動和枚舉目錄和子目錄的執行個體方法。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx
(註:以下出現的dirPath表示檔案夾路徑,filePath表示檔案路徑)
1.建立檔案夾
Directory.CreateDirectory(@"D:\TestDir");
2.建立檔案
建立檔案會出現檔案被訪問,以至於無法刪除以及編輯。建議用上using。
using (File.Create(@"D:\TestDir\TestFile.txt"));
3.刪除檔案
刪除檔案時,最好先判斷該檔案是否存在!
if (File.Exists(filePath)){ File.Delete(filePath);}
4.刪除檔案夾
刪除檔案夾需要對異常進行處理。可捕獲指定的異常。msdn:http://msdn.microsoft.com/zh-cn/library/62t64db3(v=VS.80).aspx
Directory.Delete(dirPath); //刪除空目錄,否則需捕獲指定異常處理Directory.Delete(dirPath, true);//刪除該目錄以及其所有內容
5.刪除指定目錄下所有的檔案和檔案夾
一般有兩種方法:1.刪除目錄後,建立空目錄 2.找出下層檔案和檔案夾路徑迭代刪除
1 /// <summary> 2 /// 刪除指定目錄下所有內容:方法一--刪除目錄,再建立空目錄 3 /// </summary> 4 /// <param name="dirPath"></param> 5 public static void DeleteDirectoryContentEx(string dirPath) 6 { 7 if (Directory.Exists(dirPath)) 8 { 9 Directory.Delete(dirPath);10 Directory.CreateDirectory(dirPath);11 }12 }13 14 /// <summary>15 /// 刪除指定目錄下所有內容:方法二--找到所有檔案和子檔案夾刪除16 /// </summary>17 /// <param name="dirPath"></param>18 public static void DeleteDirectoryContent(string dirPath)19 {20 if (Directory.Exists(dirPath))21 {22 foreach (string content in Directory.GetFileSystemEntries(dirPath))23 {24 if (Directory.Exists(content))25 {26 Directory.Delete(content, true);27 }28 else if (File.Exists(content))29 {30 File.Delete(content);31 }32 }33 }34 }
6.讀取檔案
讀取檔案方法很多,File類已經封裝了四種:
一、直接使用File類
1.public static string ReadAllText(string path);
2.public static string[] ReadAllLines(string path);
3.public static IEnumerable<string> ReadLines(string path);
4.public static byte[] ReadAllBytes(string path);
以上獲得內容是一樣的,只是傳回型別不同罷了,根據自己需要調用。
二、利用流讀取檔案
分別有StreamReader和FileStream。詳細內容請看代碼。
1 //ReadAllLines 2 Console.WriteLine("--{0}", "ReadAllLines"); 3 List<string> list = new List<string>(File.ReadAllLines(filePath)); 4 list.ForEach(str => 5 { 6 Console.WriteLine(str); 7 }); 8 9 //ReadAllText10 Console.WriteLine("--{0}", "ReadAllLines");11 string fileContent = File.ReadAllText(filePath);12 Console.WriteLine(fileContent);13 14 //StreamReader15 Console.WriteLine("--{0}", "StreamReader");16 using (StreamReader sr = new StreamReader(filePath))17 {18 //方法一:從流的當前位置到末尾讀取流19 fileContent = string.Empty;20 fileContent = sr.ReadToEnd();21 Console.WriteLine(fileContent);22 //方法二:一行行讀取直至為NULL23 fileContent = string.Empty;24 string strLine = string.Empty;25 while (strLine != null)26 {27 strLine = sr.ReadLine();28 fileContent += strLine+"\r\n";29 }30 Console.WriteLine(fileContent); 31 }
7.寫入檔案
寫檔案內容與讀取檔案類似,請參考讀取檔案說明。
1 //WriteAllLines 2 File.WriteAllLines(filePath,new string[]{"11111","22222","3333"}); 3 File.Delete(filePath); 4 5 //WriteAllText 6 File.WriteAllText(filePath, "11111\r\n22222\r\n3333\r\n"); 7 File.Delete(filePath); 8 9 //StreamWriter10 using (StreamWriter sw = new StreamWriter(filePath))11 {12 sw.Write("11111\r\n22222\r\n3333\r\n");13 sw.Flush();14 }
9.檔案路徑
檔案和檔案夾的路徑操作都在Path類中。另外還可以用Environment類,裡麵包含環境和程式的資訊。
1 string dirPath = @"D:\TestDir"; 2 string filePath = @"D:\TestDir\TestFile.txt"; 3 Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "檔案路徑"); 4 //獲得當前路徑 5 Console.WriteLine(Environment.CurrentDirectory); 6 //檔案或檔案夾所在目錄 7 Console.WriteLine(Path.GetDirectoryName(filePath)); //D:\TestDir 8 Console.WriteLine(Path.GetDirectoryName(dirPath)); //D: 9 //副檔名10 Console.WriteLine(Path.GetExtension(filePath)); //.txt11 //檔案名稱12 Console.WriteLine(Path.GetFileName(filePath)); //TestFile.txt13 Console.WriteLine(Path.GetFileName(dirPath)); //TestDir14 Console.WriteLine(Path.GetFileNameWithoutExtension(filePath)); //TestFile15 //絕對路徑16 Console.WriteLine(Path.GetFullPath(filePath)); //D:\TestDir\TestFile.txt17 Console.WriteLine(Path.GetFullPath(dirPath)); //D:\TestDir 18 //更改副檔名19 Console.WriteLine(Path.ChangeExtension(filePath, ".jpg"));//D:\TestDir\TestFile.jpg20 //根目錄21 Console.WriteLine(Path.GetPathRoot(dirPath)); //D:\ 22 //產生路徑23 Console.WriteLine(Path.Combine(new string[] { @"D:\", "BaseDir", "SubDir", "TestFile.txt" })); //D:\BaseDir\SubDir\TestFile.txt24 //產生隨即檔案夾名或檔案名稱25 Console.WriteLine(Path.GetRandomFileName());26 //建立磁碟上唯一命名的零位元組的臨時檔案並返回該檔案的完整路徑27 Console.WriteLine(Path.GetTempFileName());28 //返回當前系統的臨時檔案夾的路徑29 Console.WriteLine(Path.GetTempPath());30 //檔案名稱中無效字元31 Console.WriteLine(Path.GetInvalidFileNameChars());32 //路徑中無效字元33 Console.WriteLine(Path.GetInvalidPathChars());
10.檔案屬性操作
File類與FileInfo都能實現。靜態方法與執行個體化方法的區別!
1 //use File class 2 Console.WriteLine(File.GetAttributes(filePath)); 3 File.SetAttributes(filePath,FileAttributes.Hidden | FileAttributes.ReadOnly); 4 Console.WriteLine(File.GetAttributes(filePath)); 5 6 //user FilInfo class 7 FileInfo fi = new FileInfo(filePath); 8 Console.WriteLine(fi.Attributes.ToString()); 9 fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly; //隱藏與唯讀10 Console.WriteLine(fi.Attributes.ToString());11 12 //唯讀與系統屬性,刪除時會提示拒絕訪問13 fi.Attributes = FileAttributes.Archive;14 Console.WriteLine(fi.Attributes.ToString());
11.移動檔案夾中的所有檔案夾與檔案到另一個檔案夾
如果是在同一個盤符中移動,則直接調用Directory.Move的方法即可!跨盤符則使用下面遞迴的方法!
1 /// <summary> 2 /// 移動檔案夾中的所有檔案夾與檔案到另一個檔案夾 3 /// </summary> 4 /// <param name="sourcePath">源檔案夾</param> 5 /// <param name="destPath">目標檔案夾</param> 6 public static void MoveFolder(string sourcePath,string destPath) 7 { 8 if (Directory.Exists(sourcePath)) 9 {10 if (!Directory.Exists(destPath))11 {12 //目標目錄不存在則建立13 try14 {15 Directory.CreateDirectory(destPath);16 }17 catch (Exception ex)18 {19 throw new Exception("建立目標目錄失敗:" + ex.Message);20 }21 }22 //獲得源檔案下所有檔案23 List<string> files = new List<string>(Directory.GetFiles(sourcePath)); 24 files.ForEach(c =>25 { 26 string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});27 //覆蓋模式28 if (File.Exists(destFile))29 {30 File.Delete(destFile);31 }32 File.Move(c, destFile);33 });34 //獲得源檔案下所有目錄檔案35 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));36 37 folders.ForEach(c =>38 {39 string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });40 //Directory.Move必須要在同一個根目錄下移動才有效,不能在不同卷中移動。41 //Directory.Move(c, destDir);42 43 //採用遞迴的方法實現44 MoveFolder(c, destDir);45 }); 46 }47 else48 {49 throw new DirectoryNotFoundException("來源目錄不存在!");50 } 51 }
12.複製檔案夾中的所有檔案夾與檔案到另一個檔案夾
如果是需要移動指定類型的檔案或者包含某些字元的目錄,只需在Directory.GetFiles中加上查詢條件即可!
1 /// <summary> 2 /// 複製檔案夾中的所有檔案夾與檔案到另一個檔案夾 3 /// </summary> 4 /// <param name="sourcePath">源檔案夾</param> 5 /// <param name="destPath">目標檔案夾</param> 6 public static void CopyFolder(string sourcePath,string destPath) 7 { 8 if (Directory.Exists(sourcePath)) 9 {10 if (!Directory.Exists(destPath))11 {12 //目標目錄不存在則建立13 try14 {15 Directory.CreateDirectory(destPath);16 }17 catch (Exception ex)18 {19 throw new Exception("建立目標目錄失敗:" + ex.Message);20 }21 }22 //獲得源檔案下所有檔案23 List<string> files = new List<string>(Directory.GetFiles(sourcePath)); 24 files.ForEach(c =>25 { 26 string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});27 File.Copy(c, destFile,true);//覆蓋模式28 });29 //獲得源檔案下所有目錄檔案30 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath)); 31 folders.ForEach(c =>32 {33 string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });34 //採用遞迴的方法實現35 CopyFolder(c, destDir);36 }); 37 }38 else39 {40 throw new DirectoryNotFoundException("來源目錄不存在!");41 } 42 }
總結:
有關檔案的操作的內容非常多,不過幾乎都是從上面的這些基礎方法中演化出來的。比如對內容的修改,不外乎就是加上點字串操作或者流操作。還有其它一些特別的內容,等在開發項目中具體遇到後再添加。
(轉)C#檔案操作大全