使用C#遞迴刪除一個檔案夾

來源:互聯網
上載者:User

刪除檔案夾有時候並不是一件容易的事,特別是類似於boost解壓出來的檔案夾,其中的目錄和檔案太多,刪除的時候,光彈出確認介面就要等好久好久。

最理想的情況是,我選中這個目錄後,馬上可以開始刪除,然後我就可以站起來出去喝口水,或者去吃個飯,回來時世界已經清靜了。

當然了,現在win7刪除一個大目錄時,速度已經相當快了,再加上電腦速度越來越快。自己寫代碼這種事純粹是個人愛好,不見得速度比windows的刪除速度快,本文只是記錄一下這個想法的實際做法,免得需要的時候又琢磨半天。

自己建立一個視窗,用來接收選擇目錄等等操作,new 一個 DeleteRunner出來,然後把目錄的路徑傳給其Delete函數即可。

class DeleteRunner{    private string m_strRoot;    private int longDirNum = 0;    public DeleteRunner()    {    }    public void Delete(string strPath) //對外介面    {        m_strRoot = strPath;        _delete(strPath);    }    private void _delete(string strFolder)    {        //刪除長路徑, 把目錄移動到根目錄下再刪除, 防止刪除時的windows錯誤提示        if (strFolder.Length >= 160)         {            int pos = strFolder.LastIndexOf("\\");            if (pos == -1)            {                return;            }            ++longDirNum;            string strDestDir = m_strRoot + "\\" + longDirNum;            Directory.Move(strFolder, strDestDir);                            _delete(strDestDir);            return;        }        //刪除目錄下的所有檔案        string[] listFiles = Directory.GetFiles(strFolder);        if (listFiles.Length > 0)        {            for (int index = 0; index < listFiles.Length; ++index)            {                FileInfo fi = new FileInfo(listFiles[index]);                fi.Attributes = FileAttributes.Normal; //防止有唯讀檔案無法刪除                File.Delete(listFiles[index]);            }        }        //刪除此目錄下的所有目錄,即遞迴向下刪        string[] listFolders = Directory.GetDirectories(strFolder);        if (listFolders.Length > 0)        {            for (int index = 0; index < listFolders.Length; ++index)            {                _delete(listFolders[index]);            }        }        //最後刪除目前的目錄        Directory.Delete(strFolder);    }}

美中不足的時,這樣刪除時,還是會遇到一些問題,比如“目錄不是空的”等等這些提示,不過小問題就不管了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.