繁体   English   中英

从 c# Forms 应用程序运行批处理文件和命令

[英]Running batch file & commands from c# Forms application

我有以下代码:

        private void RunBatchFile()
        {
            string batchFile = "FlashDevice.bat";
            string CurrentDir = Directory.GetCurrentDirectory();
            string logFile = "\""+ CurrentDir + "\\logFile.txt\" 2>&1 ";
            string[] lines =
            {
                "cd \"c:\\Users\\thebi\\esp\\esp-idf\" ",
               // " \"c:\\WINDOWS\\system32\\cmd.exe\" /k " +
                "\"c:\\Users\\thebi\\esp\\.espressif\\idf_cmd_init.bat\" \"c:\\Users\\thebi\\AppData\\Local\\Programs\\Python\\Python37\\\" \"c:\\Program Files\\Git\\cmd\\\"  > " + logFile,
                "cd " + projPath,
                "idf.py flash -b 921600 >> " + logFile
        };
            File.WriteAllLines(batchFile, lines);

            Process proc = null;
            try
            {
                string batDir = Directory.GetCurrentDirectory();
                proc = new Process();
                proc.StartInfo.WorkingDirectory = batDir;
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.Arguments = "/c /wait " + batchFile;

                proc.Start();
                proc.WaitForExit();

               // proc.Start();
               // proc.WaitForExit();
                MessageBox.Show("Bat file executed !!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
            }


           // File.Delete(batchFile);
        }

它很好地运行了前几个命令,但似乎跳过了最后一个。 如果我打开一个空白的命令提示符并从我创建的文件(FlashDevice.bat)中一次复制一个命令,那么一切正常。 但是当我从 c# 程序运行它时,它似乎完全忽略了关键命令。

我也试过:

        proc.StartInfo.FileName = batchFile;
        proc.StartInfo.CreateNoWindow = false;
        proc.StartInfo.Arguments = "/k /wait ";

没有不同。 有经验的 c# 的人能否帮助指出错误。 谢谢。

好吧,就其价值而言,这似乎完美无缺,几乎没有那么多混乱:

    private void ProgramFirmware()
    {
        string CurrentDir = Directory.GetCurrentDirectory();
        string logFile = "\"" + CurrentDir + "\\logFile.txt\" 2>&1 ";

        string strCmdText =
            "'/c cd \"c:\\Users\\thebi\\esp\\esp-idf\" && " +
            " echo \"Setting Up environment...\" && " +
            "\"c:\\Users\\thebi\\esp\\.espressif\\idf_cmd_init.bat\" \"c:\\Users\\thebi\\AppData\\Local\\Programs\\Python\\Python37\\\" \"c:\\Program Files\\Git\\cmd\\\" > " + logFile + " && " +
            "cd " + projPath + "&& " +
            " echo \"Burning Device Firmware...\" && " +
            "idf.py flash -b 921600 >> " + logFile + "'";
        System.Diagnostics.Process.Start("CMD.exe", strCmdText);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM