C#完成平安刪除文件目次的辦法。本站提示廣大學習愛好者:(C#完成平安刪除文件目次的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成平安刪除文件目次的辦法正文
本文實例講述了C#完成平安刪除文件目次的辦法。分享給年夜家供年夜家參考。詳細剖析以下:
1. 創立文件夾 (簡略,沒多斟酌)
2. 刪除所建文件夾:為避免刪除進程中有其他過程援用該文件夾中文件,增長了對此不測情形的斟酌。
在本例中,若刪除進程中被其他過程援用,期待並輪回5次測驗考試再次刪除操作。長時光沒法被刪除,則刪除文件目次掉敗
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();
}
}
}
願望本文所述對年夜家的C#法式設計有所贊助。