using System.Diagnostics;
class Program
{
public static string RunCommand(string command)
{
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c {command}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = startInfo })
{
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
return string.IsNullOrEmpty(error) ? output : $"Error: {error}";
}
}
static void Main()
{
string result = RunCommand("dir");
Console.WriteLine(result);
}
}
/*
run:
Volume in drive C has no label.
Volume Serial Number is 97QZ-OIE1
Directory of C:\C#_ConsoleApp1\bin\Debug\net7.0
01/08/2026 10:50 AM <DIR> .
01/08/2026 10:50 AM <DIR> ..
10/31/2025 09:22 AM 434 C#_ConsoleApp1.deps.json
01/08/2026 10:50 AM 5,120 C#_ConsoleApp1.dll
01/08/2026 10:50 AM 154,624 C#_ConsoleApp1.exe
01/08/2026 10:50 AM 10,464 C#_ConsoleApp1.pdb
10/31/2025 09:22 AM 147 C#_ConsoleApp1.runtimeconfig.json
5 File(s) 170,789 bytes
2 Dir(s) 324,851,265,536 bytes free
*/