簡體   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