@manhng

Welcome to my blog!

CLI Program

June 23, 2021 10:33

CLI Program (edit)

Execute Command Prompt commands from C# - CODE-AI

  • C# code to call .exe program: Không để .exe ở sau lời gọi chương trình CLI
  • C# code to call .exe program: Có 2 cách để thực hiện, xem thêm 2 ví dụ ở dưới
  • C# code to call .exe program: Cần lưu ý vài điểm sau:
    • WorkingDirectory là folder chứa chương trình chạy, ví dụ C:\VPN\NetExtender\
    • FolderPath là folder chứa chương trình chạy, ví dụ C:\VPN\NetExtender\
    • Ở code dưới thì filePath là đường dẫn chương trình chạy, ví dụ C:\VPN\NetExtender\NECLI.exe

Example 1:

private static string CallNECLI(string param)
{
try
{
string filePath = string.Concat(Path.Combine(FolderPath, "NECLI"), ".exe");
if (!System.IO.File.Exists(filePath))
{
string str = $"File '{filePath}' does not exits";
Debug.WriteLine(str);
return str;
}

string command = string.Format("/c {0} {1}", "NECLI", param);
Debug.WriteLine(command);

var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", command)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = FolderPath
};

System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Diagnostics.Process p = System.Diagnostics.Process.Start(processInfo);
p.OutputDataReceived += (s, a) => sb.AppendLine(a.Data);
p.BeginOutputReadLine();
p.WaitForExit();

return sb.ToString();
}
catch (System.Exception ex)
{
Debug.WriteLine($"CallNECLI error, detail: {ex}");
throw;
}
}

Example 2:

 static void Main(string[] args)
{

string path = @"C:\VPN\NetExtender"; //Program: NECLI.exe

string command = @"NECLI connect -s ""server_name"" -u ""user_name"" -p ""pass_word"" -d ""domain_name""";

Process process = new Process();
process.StartInfo = new ProcessStartInfo
{
WorkingDirectory = path,
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
process.Start();
process.StandardInput.WriteLine(command);
process.StandardInput.Flush();
process.StandardInput.Close();

string result = process.StandardOutput.ReadToEnd();

process.WaitForExit();

Console.WriteLine(result);

Console.ReadLine();
}

What is CLI (w3schools.com)

For .NET Core: Command Line Interface (CLI)

CLI stands for:

  • Command Line Interface
  • Command Line Interpreter
  • Command Line Input

Categories

Recent posts