[C#] 叫用程式並等待其執行結果

有時在進行整合的時候, 須要啟動本身以外的程式並等待其執行結果. 再視結果決定行動. 在.net Framework 中, 可以利用ProcessInfo 實現.

private static string RunExternalProgram(string a_filename, string[] a_arguments, string a_workdirectory)
        {
            System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
            Info.FileName = a_filename;
            Info.Arguments = string.Join(" ", a_arguments);
            Info.WorkingDirectory = a_workdirectory;
            Info.RedirectStandardError = true;
            Info.UseShellExecute = false;
            System.Diagnostics.Process Proc;

            String errorMsg = string.Empty;

            try
            {
                Proc = System.Diagnostics.Process.Start(Info);
                errorMsg = Proc.StandardError.ReadToEnd();
                Proc.WaitForExit();

                return errorMsg;
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                throw ex;
            }
        }

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.