C#调用命令行删除文件及文件夹 您所在的位置:网站首页 win10进入命令行删除正在使用文件 C#调用命令行删除文件及文件夹

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

2024-03-16 03:45| 来源: 网络整理| 查看: 265

/// /// cmd/// public class CmdHelper{    ///     /// 命令行删除文件    ///     ///     public static void CmdDelFile(string fullPath)    {        try        {            string cmd = "del /f /q \"" + fullPath +"\"";// /Q 是静默执行            RunCmd(cmd, out string output);        }        catch(Exception ex)        {        }    }    ///     /// 命令行删除文件夹及子文件    ///     ///     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)        {        }    }    ///     /// 执行Cmd命令    ///     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)删除文件和文件夹时,如果文件只读、被占用、没有删除权限,会抛出异常



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有