• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

/// <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)删除文件和文件夹时,如果文件只读、被占用、没有删除权限,会抛出异常


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C标准函数库中获取时间与日期、对时间与日期数据操作及格式化 ...发布时间:2022-07-14
下一篇:
C/C++预定义编译宏发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap