C#實(shí)現(xiàn)安全刪除文件目錄的方法
本文實(shí)例講述了C#實(shí)現(xiàn)安全刪除文件目錄的方法。分享給大家供大家參考。具體分析如下:
1. 創(chuàng)建文件夾 (簡(jiǎn)單,沒多考慮)
2. 刪除所建文件夾:為防止刪除過程中有其他進(jìn)程引用該文件夾中文件,增加了對(duì)此意外情況的考慮。
在本例中,若刪除過程中被其他進(jìn)程引用,等待并循環(huán)5次嘗試再次刪除操作。長(zhǎng)時(shí)間無(wú)法被刪除,則刪除文件目錄失敗
using System; using System.IO; namespace Retry { class Program { static void Main(string[] args) { DirectoryInfo dirInfo = Directory.CreateDirectory(@"C:\TestDir"); string folderName = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\TestDir"; if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); Console.WriteLine("{0} created! ",folderName); } int retryTimes = 1; do { if (Directory.Exists(folderName)) { try { Console.WriteLine("Tring to delete file the {0} time.",retryTimes); Directory.Delete(folderName, true); Console.WriteLine("Deleting file successfully."); break; } catch (IOException ex) { Console.WriteLine("Exception! ", ex.ToString()); Console.WriteLine("Sleep 5 seconds and retry."); System.Threading.Thread.Sleep(5000); retryTimes++; } } else { Console.WriteLine("Delete folder successfully"); break; } } while (retryTimes <= 5); if (Directory.Exists(folderName)) Console.WriteLine("Deleting folder failed."); Console.WriteLine("Done"); Console.ReadKey(); } } }
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
webBrowser執(zhí)行js的方法,并返回值,c#后臺(tái)取值的實(shí)現(xiàn)
下面小編就為大家?guī)硪黄獁ebBrowser執(zhí)行js的方法,并返回值,c#后臺(tái)取值的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-12-12C#使用iCSharpcode進(jìn)行文件壓縮實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用iCSharpcode進(jìn)行文件壓縮實(shí)現(xiàn)方法,末尾附有完整實(shí)例,有助于大家參考借鑒,需要的朋友可以參考下2014-08-08C#實(shí)現(xiàn)chart控件動(dòng)態(tài)曲線繪制
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)chart控件動(dòng)態(tài)曲線繪制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02