본문

C#에서 외부프로그램 실행하고 결과 가져오기


일터에서 하는 일들을 효율적으로 하기 위해서 프로그램을 작성하려 하였다. 그간 배치파일로 하던 일이 있기 때문에 따로 코드를 만들필요없이 명령줄만 제대로 호출되면 된다. 이 문제는 다음과 같은 코드로 매우 쉽게 해결되었다. 참고로 ProcessStartInfo 클래스는 Diagnostics 네임스페이스 내에 있다(즉, using System.Diagnostics; 사용)

Ping 버튼을 누르면 아래의 코드가 실행되는데, 저기 google.co.kr이라고 적은 부분은 textBox1, 그 아래의 결과는 richTextBox1에 저장된다. 이 코드에서 문제라고 한다면 프로세스가 실행중일 때 화면이 멈추고, 프로세스가 종료되어야 그제서야 화면이 돌아오는데, 이는 ThreadPool을 사용해서 해결할 수 있으며, 이에대해서는 C#에서 정규표현식을 사용하는 방법과 더불어 다음 포스팅에서 언급할 것이다.

============================
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"ping.exe";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
start.Arguments = textBox1.Text;
           
using (Process process = Process.Start(start)) {
    using (StreamReader reader = process.StandardOutput) {
        richTextBox1.Text=reader.ReadToEnd();
    }
}

댓글

Holic Spirit :: Tistory Edition

design by tokiidesu. powerd by kakao.