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;

     

            }       

  • 相关阅读:
    图像全參考客观评价算法比較
    单片机project师必备的知识
    ACM-并查集之小希的迷宫——hdu1272
    ArcGIS教程:加权总和
    九度 题目1368:二叉树中和为某一值的路径
    解决solr搜索多词匹配度和排序方案
    具体解释linux文件处理的的经常使用命令
    Hotel
    Unity3D 射线指定层获取GameObject 注意 LayerMask
    ios设计一部WindowsPhone手机
  • 原文地址:https://www.cnblogs.com/mol1995/p/10461096.html
Copyright © 2011-2022 走看看