1. 程式人生 > >asp.net C# 中刪除一個資料夾裡的所有內容

asp.net C# 中刪除一個資料夾裡的所有內容

using System.IO;

public static void DeleteDir(string aimPath)
        {
            try
            {
                // 檢查目標目錄是否以目錄分割字元結束如果不是則新增之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 得到源目錄的檔案列表,該裡面是包含檔案以及目錄路徑的一個數組
                // 如果你指向Delete目標檔案下面的檔案而不包含目錄請使用下面的方法
                // string[] fileList = Directory.GetFiles(aimPath);
                string[] fileList = Directory.GetFileSystemEntries(aimPath);
                // 遍歷所有的檔案和目錄
                foreach (string file in fileList)
                {
                    // 先當作目錄處理如果存在這個目錄就遞迴Delete該目錄下面的檔案
                    if (Directory.Exists(file))
                    {
                        DeleteDir(aimPath + Path.GetFileName(file));
                    }
                    // 否則直接Delete檔案
                    else
                    {
                        File.Delete(aimPath + Path.GetFileName(file));
                    }
                }
                //刪除資料夾
                System.IO.Directory.Delete(aimPath, true);
            }
            catch
            {
               
            }
        }

例子:

protected void BtnDelete_Click(object sender, ImageClickEventArgs e)
        {
            var Row = this.UltraWebGrid1.DisplayLayout.ActiveRow;
            string brName = (string)Row.Cells.FromKey("Name").Value;
            string filename = Server.MapPath("../");
            string pathname = filename + @"backupAndRestore/" + brName;
            File.Delete(pathname);
            Response.Write("<script type='text/javascript'>window.location='frmDBBackup.aspx';</script>");
        }