C#實(shí)現(xiàn)安全刪除文件目錄的方法
本文實(shí)例講述了C#實(shí)現(xiàn)安全刪除文件目錄的方法。分享給大家供大家參考。具體分析如下:
1. 創(chuàng)建文件夾 (簡(jiǎn)單,沒(méi)多考慮)
2. 刪除所建文件夾:為防止刪除過(guò)程中有其他進(jìn)程引用該文件夾中文件,增加了對(duì)此意外情況的考慮。
在本例中,若刪除過(guò)程中被其他進(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)文章
C#實(shí)現(xiàn)數(shù)組元素的數(shù)據(jù)類型轉(zhuǎn)換方法詳解
這篇文章主要為大家介紹了C#中一維數(shù)組如何快速實(shí)現(xiàn)數(shù)組元素的數(shù)據(jù)類型的轉(zhuǎn)換,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-04-04
利用thrift實(shí)現(xiàn)js與C#通訊的實(shí)例代碼
利用thrift實(shí)現(xiàn)js與C#通訊的實(shí)例代碼,需要的朋友可以參考一下2013-04-04
winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法
這篇文章主要介紹了winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法,涉及C#窗體屬性設(shè)置的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-08-08
C#省份城市下拉框聯(lián)動(dòng)簡(jiǎn)單實(shí)現(xiàn)方法
這篇文章主要介紹了C#省份城市下拉框聯(lián)動(dòng)簡(jiǎn)單實(shí)現(xiàn)方法,涉及字典的定義與索引的用法,是非常實(shí)用的技巧,需要的朋友可以參考下2014-12-12

