zoukankan      html  css  js  c++  java
  • 整体读入cmd结果,而不是分行读入,效率极高

    public static long GetDirectorySize(string path)

            {

                long res = 0; 

                System.Diagnostics.Process p = new System.Diagnostics.Process();

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

                p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动

                p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息

                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息

                p.StartInfo.RedirectStandardError = true;//重定向标准错误输出

                p.StartInfo.CreateNoWindow = true;//不显示程序窗口

                p.Start();//启动程序

     

                //向cmd窗口发送输入信息

                string str = $"dir {path} /-c /s &exit";           

                p.StandardInput.WriteLine(str);

                //这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死

                //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

     

                p.StandardInput.AutoFlush = true;

     

                //获取cmd窗口的输出信息

                string output = p.StandardOutput.ReadToEnd(); //关键,这里是整体读入结果,而不是分行读入,否则速度会慢很多

               

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

                p.Close();

     

                string[] lines = output.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                string line = lines[lines.Length - 2]; // 倒数第二行是文件夹大小行

     

                Regex rgline = new Regex(@"^ +d+[^d]+d+[^d]+$"); //截获"             188292 个文件 91,582,418,518 字节"格式

                Regex regdig = new Regex(@"d+");

     

                if (rgline.IsMatch(line))

                {

                    var cc = regdig.Matches(line);

                    if (cc.Count == 2)

                    {

                        string k = cc[1].ToString();

                        res = Convert.ToInt64(k);

                    }

                }

     

                return res;

     

            }       

  • 相关阅读:
    JavaScript总结
    Python-模块
    在VMware软件下创建CentOs虚拟机
    python 日常一记 基础
    python request 基于unittest 请求deom
    python 日常已记 列表去重
    电话拨号器
    Axure RP使用攻略--入门级(二)线框图元件
    Axure RP使用攻略--入门级(一)
    ArcGIS Server-发布地理编码服务
  • 原文地址:https://www.cnblogs.com/mol1995/p/10461096.html
Copyright © 2011-2022 走看看