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)刪除文件和文件夾時,如果文件只讀、被占用、沒有刪除權限,會拋出異常
總結
以上是生活随笔為你收集整理的C#调用命令行删除文件及文件夹的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SAP Hybris Commerce的
- 下一篇: Maven and Ant for Hy