[No000073]C#直接删除指定目录下的所有文件及文件夹(保留目录)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 进制转换
{
class Program
{
#region 直接删除指定目录下的所有文件及文件夹(保留目录)
/// <summary>
///直接删除指定目录下的所有文件及文件夹(保留目录)
/// </summary>
/// <param name="strPath">文件夹路径</param>
/// <returns>执行结果</returns>
public static bool DeleteDir(string strPath)
{
try
{
strPath = @strPath.Trim().ToString();// 清除空格
if (System.IO.Directory.Exists(strPath))// 判断文件夹是否存在
{
string[] strDirs = System.IO.Directory.GetDirectories(strPath);// 获得文件夹数组
string[] strFiles = System.IO.Directory.GetFiles(strPath);// 获得文件数组
foreach (string strFile in strFiles)// 遍历所有子文件夹
{
System.Diagnostics.Debug.Write(strFile+"-deleted");
System.IO.File.Delete(strFile);// 删除文件夹
}
foreach (string strdir in strDirs)// 遍历所有文件
{
System.Diagnostics.Debug.Write(strdir + "-deleted");
System.IO.Directory.Delete(strdir, true);// 删除文件
}
}
return true;// 成功
}
catch (Exception Exp) // 异常处理
{
System.Diagnostics.Debug.Write(Exp.Message.ToString());// 异常信息
return false;// 失败
}
}
#endregion
static void Main(string[] args)
{
DeleteDir(@"C:\Users\HK\AppData\Local\Temp");
Console.ReadKey();
} }
}

注:无法删除被占用的文件!

上一篇:22个Photoshop网页设计教程网站推荐


下一篇:iOS dispatch_source_t的理解