日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

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

發布時間:2023/12/19 综合教程 28 生活家
生活随笔 收集整理的這篇文章主要介紹了 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#调用命令行删除文件及文件夹的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。