c# 資料夾操作
阿新 • • 發佈:2018-11-14
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Test { class Program { static void Main(string[] args) { // Create("E:\\新建"); //Delete("E:\\新建"); // Copy("E:\\新建", "E:\\haha"); } /// <summary> /// 建立資料夾 /// </summary> /// <param name="dirPath">路徑</param> public static void Create(string dirPath) {string[] paths = dirPath.Split('\\'); string path = paths[0]; for (int i = 1; i < paths.Length; i++) { path = path + "\\" + paths[i]; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } }/// <summary> /// 刪除資料夾 /// </summary> /// <param name="dirPath">路徑</param> public static void Delete(string dirPath) { if (Directory.Exists(dirPath)) { DirectoryInfo di = new DirectoryInfo(dirPath); foreach (FileInfo fi in di.GetFiles()) { fi.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { Delete(dir.FullName); } Directory.Delete(dirPath); } } /// <summary> /// 拷貝資料夾中的檔案至另外一個資料夾中 /// </summary> /// <param name="sourceDirPath">源路徑</param> /// <param name="destDirPath">目的路徑</param> public static void Copy(string sourceDirPath, string destDirPath) { if (Directory.Exists(sourceDirPath)) { if (!Directory.Exists(destDirPath)) Create(destDirPath); DirectoryInfo di = new DirectoryInfo(sourceDirPath); foreach (FileInfo fi in di.GetFiles()) { string toName = destDirPath + "\\" + fi.Name; File.Copy(fi.FullName, toName, true); } foreach (DirectoryInfo dir in di.GetDirectories()) { Copy(dir.FullName, destDirPath + dir.FullName.Replace(sourceDirPath, "")); } } } } }