i have exe file generated by the Compilation of C++ program now I want to pass arguments to the generated exe file through C# and save all of the output of exe file on a .txt file this is What i have done so far

public static string RunCmd(params int[] commands)
{
    string returnvalue = string.Empty;

    ProcessStartInfo info = new ProcessStartInfo("C:\\...\\.exe");
    info.UseShellExecute = false;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;

    using (Process process = Process.Start(info))
    {
        StreamWriter sw = process.StandardInput;
        StreamReader sr = process.StandardOutput;

        //foreach (int command in commands)
        //{
        //    sw.WriteLine(command);
        //}
        for (int i = 0; i < commands.Length; i++)
        {
            sw.WriteLine(commands[i]);
        }

        sw.Close();
        returnvalue = sr.ReadToEnd();
        process.Close();
        System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\..\\.txt");
        file.WriteLine(returnvalue);

        file.Close();



        return returnvalue;

}

it work well for a single argument but whenever i try to enter multiple Arguments,it just opens the .exe file and not work further

Have you tried using the Arguments property of the ProcessStartInfo property of the Process class? It accepts a string of arguments for the process.

Edited 2 Years Ago by tinstaafl

yes i have tried it but still got the same issue
this code is working fine for a program that takes only one number as a input in its C++ program but whenever i try it on some other program that takes two numbers as a input .it doesnt work well and just opens that program .exe file

How are you delimiting the arguments? c++ uses whitespace.

Your code would look something like this:

public static string RunCmd(params int[] commands)
{
    string returnvalue = string.Empty;
    ProcessStartInfo info = new ProcessStartInfo("C:\\...\\.exe");
    info.UseShellExecute = false;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.CreateNoWindow = true;
    string newarguments = "";
    foreach(int i in commands)
    {
        newarguments += i.ToString() + " ";
    }
    info.Arguments = newarguments.Trim();
    using (Process process = Process.Start(info))
    {
        StreamReader sr = process.StandardOutput;
        returnvalue = sr.ReadToEnd();
        process.Close();
        System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\..\\.txt");
        file.WriteLine(returnvalue);
        file.Close();
        return returnvalue;
}

Edited 2 Years Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.