【问题描述】:
删除指定目录但是目录下面可能包含一些子目录以及文件,C#自带的【Directory.Delete】只能删除空目录,所以首先想到的的方法就是通过【递归或循环】+【Directory.Delete】+【File.Delete】逐个删除。思考后觉得如果通过命令行删除的话,可能会更快捷方便,调查后发现命令行: 【rd /S/Q "XXXX"】(XXXX代指目录)可以实现。
【注意点】:这个命令无法删除带空格的目录
无法删除带空格目录的解决办法:加上双引号
【代码】:
/// <summary>
/// 删除目录
/// </summary>
/// <param name="directory">目录路径</param>
static bool DelDirectoryByCmd(string directory)
{
if (!Directory.Exists(directory))
return true;
return RunPro("cmd.exe", string.Format("rd /S/Q \"{0}\"&exit", directory));
}
/// <summary>
/// 运行exe
/// </summary>
/// <param name="proName">程序名</param>
/// <param name="args">参数</param>
/// <returns></returns>
static bool RunPro(string proName, string args)
{
Process process = new Process();
try
{
//通过命令行删除目录
process.StartInfo.FileName = proName;
//是否使用操作系统shell启动
process.StartInfo.UseShellExecute = false;
// 接受来自调用程序的输入信息
process.StartInfo.RedirectStandardInput = true;
//输出信息
process.StartInfo.RedirectStandardOutput = true;
// 输出错误
process.StartInfo.RedirectStandardError = true;
//不显示程序窗口
process.StartInfo.CreateNoWindow = true;
//启动程序
process.Start();
//写入命令 确保删除当前目录以及子目录
process.StandardInput.WriteLine(args);
process.StandardInput.AutoFlush = true;
//等待程序执行完退出进程
process.WaitForExit();
}
catch { return false; }
finally
{
process.Close();
}
return true;
}