การ execute command จาก C#
code ข้างล่างเราจะสร้าง process แล้วใส่คำสั่งและทำการ execute ส่วนผลลัำพธ์ที่ได้จากการ execute จะเก็บไว้ใน string variable ที่สามารถน้ำไปใช้อ้างอิืงต่อไปได้ การ execute ด้วย command นั้นเกิดขึ้นได้สองวิธีคือ synchronously และ asynchronously ใน asynchronously command เราแค่ใส่ค่ำสั่งที่ต้องการ execute โดยมันจะใช้ thread ทำงานแยกออกไปต่างหาก
Code ด้านล่างเป็นแบบ synchronously command
public void ExecuteCommandSync(object command) { try { // create the ProcessStartInfo using "cmd" as the program to be run, // and "/c " as the parameters. // Incidentally, /c tells cmd that we want it to execute the command that follows, // and then exit. System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); // The following commands are needed to redirect the standard output. // This means that it will be redirected to the Process.StandardOutput StreamReader. procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; // Do not create the black window. procStartInfo.CreateNoWindow = true; // Now we create a process, assign its ProcessStartInfo and start it System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); // Get the output into a string string result = proc.StandardOutput.ReadToEnd(); // Display the command output. Console.WriteLine(result); } catch (Exception objException) { // Log the exception } }
code ข้างบนเราทำการกำหนดคำสั่งลงไปโดบเฉพาะ และ ให้ procStartInfo.RedirectStandardOutput ถูก set ให้เป็น true เพราะเราต้องการให้ให้ output เป็นวิธีของการแสดงผลจากหน้าต่าง cmd มาเป็น StreamReader, ส่วน procStartInfo.CreateNoWindow ถูก set ให้เป็น true เพราะเราไม่ต้องการให้หน้าต่าง cmd แสดงออกมา(หน้าต่างดำๆนั่นแหละ) และมันจะประมวลผลเสร็จแบบเงียบๆ ไม่ให้เรารู้ สำหรับ code ข้างล่างต่อไปก็ึเป็นแบบ asynchronously command
public void ExecuteCommandAsync(string command) { try { //Asynchronously start the Thread to process the Execute command request. Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync)); //Make the thread as background thread. objThread.IsBackground = true; //Set the Priority of the thread. objThread.Priority = ThreadPriority.AboveNormal; //Start the thread. objThread.Start(command); Console.WriteLine("Done"); } catch (ThreadStartException objException) { // Log the exception } catch (ThreadAbortException objException) { // Log the exception } catch (Exception objException) { // Log the exception } }
ถ้าเราลองสังเกตุดีๆแล้ว การ execute แบบ asynchronous จริงๆแล้ว ก็ไปเรียกใช้การ execute แบบ synchronous แต่จะไปเรียกใช้ใน thread นั่นเอง จากสองตัวอย่างข้างบน เราจะได้ผลลัพธ์สองแบบ โดยป้อนคำสั่ง “dir” คือ แบบแรกจะแสดงผลลัพธ์ทันทีหลังจาก run ส่วนแบบที่สอง จะแสดงผลลัพธ์หลังจากสถาณะ “Done”