Description C # Call an external process

Source: Internet
Author: User

C # I can find a lot of classes that call external processes on the Internet. Why do I need to write them again? It is because I recently copied a simple routine from the Internet and used it in the project, after studying for a long time, I solved these problems. So I plan to write such a blog post to explain what problems will C # encounter when calling an external process that is so simple, I also hope that the relatively complete Class I have written can save some brain cells for the software developers so that they can concentrate their strength to solve the truly advanced and complex software problems.

Before getting started, let's take a look at the common functions that execute external processes on the Internet.

 
 
  1. PrivatestringRunCmd (stringcommand)
  2. {
  3. // Process example
  4. Processp=NewProcess();
  5.  
  6. P. StartInfo. FileName="Cmd.exe"; // Determine the program name
  7. P. StartInfo. Arguments="/C"+ Command; // determine the program command line
  8. P. StartInfo. UseShellExecute=False; // Use of Shell
  9. P. StartInfo. RedirectStandardInput=True; // Redirect Input
  10. P. StartInfo. RedirectStandardOutput=True; // Redirect output
  11. P. StartInfo. RedirectStandardError=True; // Redirect Output Error
  12. P. StartInfo. CreateNoWindow=True; // Set to not display the window
  13.  
  14. P. Start (); // 00
  15.  
  16. // P. StandardInput. WriteLine (command); // you can enter the command to be executed in this way.
  17. // P. StandardInput. WriteLine ("exit"); // you must add Exit or the next program line.
  18.  
  19. Returnp. StandardOutput. ReadToEnd (); // output the stream to obtain the command line result
  20.  
  21. }

This method should be a common method for calling external processes in C #. I have been calling external processes in this way and have never encountered any problems. However, the external process called this time is special, and two problems occur when this method is used.

The first problem is that the called external process sometimes suffers an exception. When an exception occurs, an error report box will pop up in Windows. The program then hangs there and must be manually intervened. This problem is better solved. Set the registry in the program.

The second problem is that C # calling an external process is a console process), the program will be blocked in p. standardOutput. the ReadToEnd (); statement can never come out, and the called console program is also suspended. However, the console process can be executed normally in CMD. Later, it seems that some materials found that the original cause was that a large number of strings were output in the console of the console. After the pipeline was redirected, the calling program did not promptly retrieve the output data in the pipeline, leading to blocking of the pipeline, the program is suspended. There is another problem here. Although we haven't met this time, there are other people on the Internet, that is, the error message pipeline will be blocked if the data is not retrieved in time, in addition, if you want to extract data from two pipelines at the same time, you must use an auxiliary thread.

The question is over. The complete code for this class is provided below.

 
 
  1. usingSystem;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Text;  
  4. usingSystem.Runtime.InteropServices;  
  5. usingSystem.Threading;  
  6.  
  7. namespaceLaboratory.Process  
  8. {  
  9. classReadErrorThread  
  10. {  
  11. System.Threading.Threadm_Thread;  
  12. System.Diagnostics.Processm_Process;  
  13. Stringm_Error;  
  14. boolm_HasExisted;  
  15. objectm_LockObj=newobject();  
  16.  
  17. publicStringError  
  18. {  
  19. get  
  20. {  
  21. returnm_Error;  
  22. }  
  23. }  
  24.  
  25. publicboolHasExisted  
  26. {  
  27. get  
  28. {  
  29. lock(m_LockObj)  
  30. {  
  31. returnm_HasExisted;  
  32. }  
  33. }  
  34.  
  35. set  
  36. {  
  37. lock(m_LockObj)  
  38. {  
  39. m_HasExisted=value;  
  40. }  
  41. }  
  42. }  
  43.  
  44. privatevoidReadError()  
  45. {  
  46. StringBuilderstrError=newStringBuilder();  
  47. while(!m_Process.HasExited)  
  48. {  
  49. strError.Append(m_Process.StandardError.ReadLine());  
  50. }  
  51.  
  52. strError.Append(m_Process.StandardError.ReadToEnd());  
  53.  
  54. m_Error=strError.ToString();  
  55. HasExisted=true;  
  56. }  
  57.  
  58. publicReadErrorThread(System.Diagnostics.Processp)  
  59. {  
  60. HasExisted=false;  
  61. m_Error="";  
  62. m_Process=p;  
  63. m_Thread=newThread(newThreadStart(ReadError));  
  64. m_Thread.Start();  
  65. }  
  66.  
  67. }  
  68.  
  69. classRunProcess  
  70. {  
  71. privateStringm_Error;  
  72. privateStringm_Output;  
  73.  
  74. publicStringError  
  75. {  
  76. get  
  77. {  
  78. returnm_Error;  
  79. }  
  80. }  
  81.  
  82. publicStringOutput  
  83. {  
  84. get  
  85. {  
  86. returnm_Output;  
  87. }  
  88. }  
  89.  
  90. publicboolHasError  
  91. {  
  92. get  
  93. {  
  94. returnm_Error!=""&&m_Error!=null;  
  95. }  
  96. }  
  97.  
  98. publicvoidRun(StringfileName,Stringpara)  
  99. {  
  100. StringBuilderoutputStr=newStringBuilder();  
  101.  
  102. try  
  103. {  
  104. //disabletheerrorreportdialog.  
  105. //reference:http://www.devcow.com/blogs/adnrg/archive/2006/07/14/
    Disable-Error-Reporting-Dialog-for-your-application-with-the-registry.aspx  
  106. Microsoft.Win32.RegistryKeykey;  
  107. key=Microsoft.Win32.Registry.LocalMachine.OpenSubKey
    (@"software\microsoft\PCHealth\ErrorReporting\",true);  
  108. intdoReport=(int)key.GetValue("DoReport");  
  109.  
  110. if(doReport!=0)  
  111. {  
  112. key.SetValue("DoReport",0);  
  113. }  
  114.  
  115. intshowUI=(int)key.GetValue("ShowUI");  
  116. if(showUI!=0)  
  117. {  
  118. key.SetValue("ShowUI",0);  
  119. }  
  120. }  
  121. catch  
  122. {  
  123. }  
  124.  
  125.  
  126. m_Error="";  
  127. m_Output="";  
  128. try  
  129. {  
  130. System.Diagnostics.Processp=newSystem.Diagnostics.Process();  
  131.  
  132. p.StartInfo.FileName=fileName;  
  133. p.StartInfo.Arguments=para;  
  134. p.StartInfo.UseShellExecute=false;  
  135. p.StartInfo.RedirectStandardInput=true;  
  136. p.StartInfo.RedirectStandardOutput=true;  
  137. p.StartInfo.RedirectStandardError=true;  
  138. p.StartInfo.CreateNoWindow=true;  
  139.  
  140. p.Start();  
  141.  
  142. ReadErrorThreadreadErrorThread=newReadErrorThread(p);  
  143.  
  144. while(!p.HasExited)  
  145. {  
  146. outputStr.Append(p.StandardOutput.ReadLine()+"\r\n");  
  147. }  
  148.  
  149. outputStr.Append(p.StandardOutput.ReadToEnd());  
  150.  
  151. while(!readErrorThread.HasExisted)  
  152. {  
  153. Thread.Sleep(1);  
  154. }  
  155.  
  156. m_Error=readErrorThread.Error;  
  157. m_Output=outputStr.ToString();  
  158. }  
  159. catch(Exceptione)  
  160. {  
  161. m_Error=e.Message;  
  162. }  
  163. }  
  164.  
  165. }  
  166. }  
  1. Analysis of C # Insecure code
  2. Analysis on C # Calling ImageAnimator
  3. C # connect to Access and SQL Server databases
  4. C # fixed and active Variables
  5. Describes the value types in C #.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.