C# 으로 윈도우 명령어 CMD 실행해보자 !!

2020. 12. 21. 14:23C#

728x90
반응형

 

 

 

CMD명령어를 실행하기 위해 간단히 수행하기 위해 코드 작성

/// <summary>
/// textKey : 실행할 명령어 
/// </summary>
/// <param name="textKey"></param>
/// <returns></returns>
public string executeCMD(string textKey)
{
    ProcessStartInfo pri = new ProcessStartInfo();
    Process pro = new Process();

    pri.FileName = @"cmd.exe";
    pri.CreateNoWindow = true;
    pri.UseShellExecute = false;

    pri.RedirectStandardInput = true;                //표준 출력을 리다이렉트
    pri.RedirectStandardOutput = true;
    pri.RedirectStandardError = true;

    pro.StartInfo = pri;
    pro.Start();   //어플리케이션 실

    pro.StandardInput.Write(textKey + Environment.NewLine);
    pro.StandardInput.Close();

    System.IO.StreamReader sr = pro.StandardOutput;

    string resultValue = sr.ReadToEnd();
    pro.WaitForExit();
    pro.Close();

    return resultValue == "" ? "" : resultValue;

}

예를 들어 adb shell 이라는 명령어를 날리고 싶을 때 는 아래와 같이 실행하면 된다.

string resultText = executeCMD("adb Shell");

richTextBox1.AppendText(resultText);

 

나 같은 경우는 프로그램 리소스에 allpairs라는 실행 파일을 넣고 별도로 사용자가 allpairs.exe 가 없어도

실행이 가능하도록 프로그램 자체에 exe를 내장해서 실행하는 방식을 선택 했다.

// return 받았을 때의 경로는 대략 
// C:\Users\ww\source\repos\Timing_Check\SunbaeTool\bin\Debug\Resources\allpairs.exe
// 위 와 같이 나온다.
private string GetResourceFileName()
{
    String strAppPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
    String strFilePath = Path.Combine(strAppPath, "Resources");
    String strFullFilename = Path.Combine(strFilePath, "allpairs.exe"); // Resource에 담겨진 allpair의 경로를 exe 에서 바로 가져오기 위해 path를 가져옴..
    
    return strFullFilename == "" ? "" : strFullFilename;
}

예를 들어

allpairs 라는 Tool로 어떠한 명령어를 실행하는 프로그램을 만든다 가정하면 아래와 같이 사용할 수 있겠다.

※ 물론 아래 코드는 완벽히 동작하는 것이 아닌 예시를 위한 코드이므로 제대로 동작이 안될 수 있다.

 

private void btn_execute_Click(object sender, EventArgs e)
{

    string fciv = GetResourceFileName();

    if (lst_fileList.Items.Count == 0)
    {
        MessageBox.Show("진행 할 File을 올리고 다시 시도해주세요.");
        return;
    }
    else
    {
        foreach (string s in lst_fileList.Items)
        {
            string filePath = Path.Combine(s);
            string resultText = executeCMD(filePath + " " + " oldFile.txt " + ">" + " newfile.txt");

            // ALLPAIRS. exe <input file>  > <Output file>
            // Example ALLPAIRS VARS.TXT > TESTCASES.TXT


            // 테스트 코드 (쓸 때 없는 텍스트를 지워주기 위해 임시로 테스트 )
            string cutText = resultText;
            string outputText;
            outputText = cutText.Substring(cutText.IndexOf("All rights reserved."));
            outputText = outputText.Replace("All rights reserved.", string.Empty);
            //outputText = cutText.Substring(50, cutText.Length);

            richTextBox1.AppendText(Environment.NewLine + outputText);
            richTextBox1.AppendText(string.Format("{0}", "--------------------") + Environment.NewLine);

        }

    }

}

 

 

 

728x90
반응형