2

New to programming and I'm writing a process which is supposed to open up the cmd prompt, run the command

"/k nslookup 123.123.123.123;

And then redirect the standard output into a string so the data can be manipulated. I've tried various combinations but cannot get the program to output anything except my last line of "Press any key to close".

I feel as though I'm missing something very simple as I can't find anything wrong with my code. Does anyone have any suggestions?

try
        {
            string strCmdText;
            strCmdText = "/k nslookup 123.123.123.123";

            // Start the process.
            Process p = new Process();

            //The name of the application to start, or the name of a document 
            p.StartInfo.FileName = "C:/Windows/System32/cmd.exe";
            // On start run the string strCmdText as a command
            p.StartInfo.Arguments = strCmdText;

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;   

            p.Start();

            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadLine();
            p.WaitForExit();
            Console.WriteLine(output);

        }
        catch (Exception)
        {
            Console.WriteLine( "error");
        }

//Wait for user to press a button to close window
        Console.WriteLine("Press any key...");
        Console.ReadLine();

1 Answers1

0

I think it is because the command prompt is not exiting. Instead of passing arguments, write them to the standard input and then exit, like this:

        p.StartInfo.Arguments = "";

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.CreateNoWindow = true;   

        p.Start();

        p.StandardInput.WriteLine("/k nslookup 123.123.123.123");
        p.StandardInput.WriteLine("exit");

        // Read the output stream first and then wait.
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        Console.WriteLine(output);
Fiona - myaccessible.website
  • 14,481
  • 16
  • 82
  • 117
  • Nice catch but I actually had that originally and forgot to change it back. Figured I'd play around to see if I could get anything to work. Unfortunately, ReadToEnd does not solve the issue. – user2428835 Aug 02 '13 at 13:25