C#调用命令行删除文件及文件夹

/// <summary>

/// cmd

/// </summary>

public class CmdHelper

{

/// <summary>

/// 命令行删除文件

/// </summary>

/// <param name="fullPath"></param>

public static void CmdDelFile(string fullPath)

{

try

{

string cmd = "del /f /q \"" + fullPath +"\"";// /Q 是静默执行

RunCmd(cmd, out string output);

}

catch(Exception ex)

{

}

}

/// <summary>

/// 命令行删除文件夹及子文件

/// </summary>

/// <param name="fullPath"></param>

public static void CmdDelDir(string fullPath)

{

try

{

string cmd = "rmdir /s/q \""+fullPath+"\"";// /S 删除文件夹及文件夹下的子文件和文件夹

RunCmd(cmd, out string output);

Logger.Write(typeof(CmdHelper), EnumLogLevel.Info, output);

}

catch(Exception ex)

{

}

}

/// <summary>

/// 执行Cmd命令

/// </summary>

public static void RunCmd(string cmd, out string output)

{

cmd = cmd.Trim().TrimEnd('&') + "&exit";//不管命令是否成功,均质性exit

using (Process p = new Process())

{

string cmdPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");

p.StartInfo.FileName = "cmd.exe";

p.StartInfo.Arguments = "/c " + cmdPath;

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.CreateNoWindow = true;

p.StartInfo.Verb = "RunAs";

p.Start();

p.StandardInput.WriteLine(cmd);

p.StandardInput.AutoFlush = true;

output = p.StandardOutput.ReadToEnd();

p.WaitForExit();//等待程序执行完,退出进程

p.Close();

}

}

}

使用这种方式的好处是:

1、可以删除只读文件

2、可以删除正在打开的文件(调用删除后,关闭打开的文件,自动消失)

3、主程序已管理员身份运行,可删除有管理员权限的文件

4、即便是删除不掉文件,不影响程序继续运行

对比:

使用File.Delete(filePah) 和Dierctory.Delete(dirPath,true)删除文件和文件夹时,如果文件只读、被占用、没有删除权限,会抛出异常