1.前言:
檔案的處理常需要操作文件及目錄,本範例將常用的功能列出,方便使用。
2.說明:
在.NET中操作檔案及目錄最主要的是File及Directory兩個類別,均在System.IO的命名空間下。
程式碼:
//建立新檔案 private static void CreateFile(string fileName) { FileStream fs = File.Create(fileName); fs.Close(); } //讀檔案 private static string ReadFile(string fileName) { string content = ""; content = File.ReadAllText(fileName); return content; } //刪除檔案 private static void DeleteFile(string fileName) { if (File.Exists(fileName)) { File.Delete(fileName); } } //複製檔案 private static void CopyFile(string sourceFileName, string destFileName) { if (File.Exists(sourceFileName)) { File.Copy(sourceFileName, destFileName); } } //移動檔案 private static void MoveFile(string sourceFileName, string destFileName) { if (File.Exists(sourceFileName)) { File.Move(sourceFileName, destFileName); } } //建立目錄 private static void CreateDirectory(string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } //刪除目錄,recursive為True時,直接刪除目錄及其目錄下所有文件或子目錄;recursive為False時,需先將目錄下所有文件或子目錄刪除 private static void DeleteDirectory(string path, bool recursive) { if (Directory.Exists(path)) { if (recursive) { Directory.Delete(path, true); } else { Console.WriteLine("Please delete the files or sub directory first!"); } } } //移動目錄 private static void MoveDirectory(string sourceDirName, string destDirName) { if (Directory.Exists(sourceDirName)) { Directory.Move(sourceDirName, destDirName); } } //讀取目錄下所有子目錄 private static ArrayList GetDirectories(string path) { ArrayList directories = new ArrayList(); if (Directory.Exists(path)) { directories.AddRange(Directory.GetDirectories(path)); } return directories; } //讀取目錄下所有檔案 private static ArrayList GetFiles(string path) { ArrayList files = new ArrayList(); if (Directory.Exists(path)) { files.AddRange(Directory.GetFiles(path)); } return files; }
文章標籤
全站熱搜
留言列表