Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to run a Command and retrieve data from it ?

How to run a Command and retrieve data from it ?

Scheduled Pinned Locked Moved C#
helptutorialquestion
18 Posts 5 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A All Time Programming

    Hello, I want to run a Command from command promt and want its output and maipulate its output. If required, want to close the process and display error or appropriate message. How is that possible. Any help is highly appreciated. I am stuck with this and would be glad if any body helps me solve my problem. Thanks Thanks & Regards,

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #5

    If you are starting the process from a C# app, then you could use the Process.StandardOutput[^] property to capture the command output and do what you like with it. There is an example in the link. The other option is to start the command in a command prompt and pipe it's output to your app. That would work with a console app, but I've never needed to try it with a WinForms.

    Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    A 1 Reply Last reply
    0
    • OriginalGriffO OriginalGriff

      If you are starting the process from a C# app, then you could use the Process.StandardOutput[^] property to capture the command output and do what you like with it. There is an example in the link. The other option is to start the command in a command prompt and pipe it's output to your app. That would work with a console app, but I've never needed to try it with a WinForms.

      Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

      A Offline
      A Offline
      All Time Programming
      wrote on last edited by
      #6

      Thanks OriginalGriff, I coded the foloowing : processInfo = new ProcessStartInfo("cmd.exe", "/C " + command); sb = new StringBuilder(); processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.CreateNoWindow = true; process = Process.Start(processInfo); process.BeginOutputReadLine(); process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived); public string ErrorMessage { get { return errorMsg; } set { errorMsg = value; } } private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { errorMsg = ""; connected = false; string d = e.Data; if (!string.IsNullOrEmpty(d)) { if (sb != null) sb.Append(d + "\n"); Console.WriteLine("LINE = " + d); // I see each line if (d.IndexOf("Initialization Completed") > 0) { connected = true; Console.WriteLine("********* Connected = " + connected); } else if (isInValidLine(d)) { //throw new Exception(d); connected = false; errorMsg = d; return; } } } private bool isInValidLine(string line) { if (line.IndexOf("Cannot load file") > 0) { errorMsg = line; return true; } return false; } The output that I see is : LINE = Thu Feb 03 17:22:28 2011 Cannot load file path (null) (SSL_CTX_load_verify_locations): error:02001002:system library:fopen:No such file or directory: error:2006D080:BIO routines:BIO_new_file:no such file: error:0B084002: Based on the above code and output, isInValidLine() should find the text "Cannot load file" and errorMsg should be set to the line and it should return true. My Implementation :

              while (!oc.Connected)
              {
                  timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
                  if (timepassed > timeout)
                  {
                      oc.DisconnectServer();
                      connectedToVpn = false
      
      OriginalGriffO 1 Reply Last reply
      0
      • A All Time Programming

        Thanks OriginalGriff, I coded the foloowing : processInfo = new ProcessStartInfo("cmd.exe", "/C " + command); sb = new StringBuilder(); processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.CreateNoWindow = true; process = Process.Start(processInfo); process.BeginOutputReadLine(); process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived); public string ErrorMessage { get { return errorMsg; } set { errorMsg = value; } } private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { errorMsg = ""; connected = false; string d = e.Data; if (!string.IsNullOrEmpty(d)) { if (sb != null) sb.Append(d + "\n"); Console.WriteLine("LINE = " + d); // I see each line if (d.IndexOf("Initialization Completed") > 0) { connected = true; Console.WriteLine("********* Connected = " + connected); } else if (isInValidLine(d)) { //throw new Exception(d); connected = false; errorMsg = d; return; } } } private bool isInValidLine(string line) { if (line.IndexOf("Cannot load file") > 0) { errorMsg = line; return true; } return false; } The output that I see is : LINE = Thu Feb 03 17:22:28 2011 Cannot load file path (null) (SSL_CTX_load_verify_locations): error:02001002:system library:fopen:No such file or directory: error:2006D080:BIO routines:BIO_new_file:no such file: error:0B084002: Based on the above code and output, isInValidLine() should find the text "Cannot load file" and errorMsg should be set to the line and it should return true. My Implementation :

                while (!oc.Connected)
                {
                    timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
                    if (timepassed > timeout)
                    {
                        oc.DisconnectServer();
                        connectedToVpn = false
        
        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #7

        I can't see anything too obvious with the code as it stands (but remmebr to check the "use HTML in this post" option at the bottom, and use "code block" rather than "inline code" next time). If you are getting the line printed - and it appears you are - then it isn't obvious what is happening. Have you tried putting a breakpoint at the start of Process_OutputDataReceived and stepping through?

        Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        A 1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          I can't see anything too obvious with the code as it stands (but remmebr to check the "use HTML in this post" option at the bottom, and use "code block" rather than "inline code" next time). If you are getting the line printed - and it appears you are - then it isn't obvious what is happening. Have you tried putting a breakpoint at the start of Process_OutputDataReceived and stepping through?

          Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

          A Offline
          A Offline
          All Time Programming
          wrote on last edited by
          #8

          Hmm, the class that handles the conection is in a library. When i added break in Process_OutputDataReceived (before execution & while execution), the app doesn't print any Line on Console. I removed the break and tried again then it showed the LINE = on console. How to add breakpoint in a library class whose dll is included in main project. While degbuging the dll class comes normally and does the debugging. How to handle this ? Is it due to the class is in a library ?

          Thanks & Regards,

          OriginalGriffO 1 Reply Last reply
          0
          • A All Time Programming

            Hmm, the class that handles the conection is in a library. When i added break in Process_OutputDataReceived (before execution & while execution), the app doesn't print any Line on Console. I removed the break and tried again then it showed the LINE = on console. How to add breakpoint in a library class whose dll is included in main project. While degbuging the dll class comes normally and does the debugging. How to handle this ? Is it due to the class is in a library ?

            Thanks & Regards,

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #9

            All Time Programming wrote:

            When i added break in Process_OutputDataReceived (before execution & while execution), the app doesn't print any Line on Console. I removed the break and tried again then it showed the LINE = on console.

            That implies it hit the breakpoint - did you try switching to VS and looking at the library code where you put the BP? I tried your code on my machine - using "dir" as the command, and a file size and date for the comparison - and it worked fine. You need to look at the data you are comparing against, I think: are those really spaces for example? Or: are you using the release version of the library in the app, and modifying the debug version?

            Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            A 1 Reply Last reply
            0
            • A All Time Programming

              Hello, I want to run a Command from command promt and want its output and maipulate its output. If required, want to close the process and display error or appropriate message. How is that possible. Any help is highly appreciated. I am stuck with this and would be glad if any body helps me solve my problem. Thanks Thanks & Regards,

              P Online
              P Online
              PIEBALDconsult
              wrote on last edited by
              #10

              Maybe this[^] is what you want.

              1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                All Time Programming wrote:

                When i added break in Process_OutputDataReceived (before execution & while execution), the app doesn't print any Line on Console. I removed the break and tried again then it showed the LINE = on console.

                That implies it hit the breakpoint - did you try switching to VS and looking at the library code where you put the BP? I tried your code on my machine - using "dir" as the command, and a file size and date for the comparison - and it worked fine. You need to look at the data you are comparing against, I think: are those really spaces for example? Or: are you using the release version of the library in the app, and modifying the debug version?

                Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                A Offline
                A Offline
                All Time Programming
                wrote on last edited by
                #11

                >> Or: are you using the release version of the library in the app, and modifying the debug version? What do you mean ? I change the code in library and build it. The reference is added in main application. I build the main app, which updates the dll file and I execute the application. I checked the dll file date/time in main app, its of Release version of library. The library & app is in Release version. Should they be in Debug version ? How to change them ? The spacing must not be a problem as I copy from the output only and put in my if to look for indexOf. But yes, I think that applying BP on 1st line of Process_OutputDataReceived while execution helps. It got the "Cannot load file..." line and it went in isInvalid, went inside that if, changed "connected = false", and for the next line

                            else if (isInValidLine(d))
                            {
                                //throw new Exception(d);
                                connected = false;     // MADE THIS
                                errorMsg = d;          // EXECUTED THIS ALSO BUT AGAIN VALUE = ""
                                return;
                            }
                
                
                    private bool isInValidLine(string line)
                    {
                        if (line.IndexOf("Cannot load CA certificate file") > 0)
                        {
                            errorMsg = line;   // EXECUTED THIS, BUT VALUE REMAINED ""
                            return true;
                        }
                        return false;
                    }
                

                i GUESS i GOT TO debug more carefully. AND should I remove & add refernce everytime I buid the library ?

                Thanks & Regards,

                OriginalGriffO 1 Reply Last reply
                0
                • A All Time Programming

                  >> Or: are you using the release version of the library in the app, and modifying the debug version? What do you mean ? I change the code in library and build it. The reference is added in main application. I build the main app, which updates the dll file and I execute the application. I checked the dll file date/time in main app, its of Release version of library. The library & app is in Release version. Should they be in Debug version ? How to change them ? The spacing must not be a problem as I copy from the output only and put in my if to look for indexOf. But yes, I think that applying BP on 1st line of Process_OutputDataReceived while execution helps. It got the "Cannot load file..." line and it went in isInvalid, went inside that if, changed "connected = false", and for the next line

                              else if (isInValidLine(d))
                              {
                                  //throw new Exception(d);
                                  connected = false;     // MADE THIS
                                  errorMsg = d;          // EXECUTED THIS ALSO BUT AGAIN VALUE = ""
                                  return;
                              }
                  
                  
                      private bool isInValidLine(string line)
                      {
                          if (line.IndexOf("Cannot load CA certificate file") > 0)
                          {
                              errorMsg = line;   // EXECUTED THIS, BUT VALUE REMAINED ""
                              return true;
                          }
                          return false;
                      }
                  

                  i GUESS i GOT TO debug more carefully. AND should I remove & add refernce everytime I buid the library ?

                  Thanks & Regards,

                  OriginalGriffO Offline
                  OriginalGriffO Offline
                  OriginalGriff
                  wrote on last edited by
                  #12

                  If your library is part of the same solution as your app, then they will both be Release or Debug together: Normally I have separate solutions, and issue the release version of a library for apps to use, while I continue changes in the debug version. In your case, that doesn't apply! If you mean that errorMsg remained empty after executing the code, could it be that the next line to be received (whether it is blank or not) starts off by setting errorMsg = ""; perhaps? Move your Console.WriteLine to immediately before the first if and see what happens.

                  Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  A 2 Replies Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    If your library is part of the same solution as your app, then they will both be Release or Debug together: Normally I have separate solutions, and issue the release version of a library for apps to use, while I continue changes in the debug version. In your case, that doesn't apply! If you mean that errorMsg remained empty after executing the code, could it be that the next line to be received (whether it is blank or not) starts off by setting errorMsg = ""; perhaps? Move your Console.WriteLine to immediately before the first if and see what happens.

                    Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                    A Offline
                    A Offline
                    All Time Programming
                    wrote on last edited by
                    #13

                    Both are of different solutions. But yes, realized during debugging & removed the errorMsg = "" & connected = false lines. And now I see that errorMsg has value in it. Implementaion PART :

                                    try
                                    {
                                        //conThread = new Thread(new ThreadStart(StartConnect));
                                        //conThread.Start();
                                        StartConnect();
                                    }
                                    catch (ThreadAbortException te)
                                    {
                                        Console.WriteLine("Abort Exception CAUGHT");
                                    }
                                    catch (Exception ex)
                                    {
                                        string msg = ex.Message;
                                        if (msg.Equals("NotConnectedException"))
                                            MessageBox.Show("Error connecting to the Server : Connection Time Out \\n Unable to connect to the Server", "Time Out", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        else if (msg.IndexOf("Cannot load CA certificate file") > 0)
                                            MessageBox.Show("Error connecting to the Server : Problem with Certificate File \\n Unable to Load or Find required Certificate file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        else if (msg.IndexOf("Error opening 'Auth' auth file:") > 0)
                                            MessageBox.Show("Error connecting to the Server : Problem with Authentication File \\n Unable to Load or Find required Authentication file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        else if (msg.IndexOf("Error opening configuration file:") > 0)
                                            MessageBox.Show("Error connecting to the Server : Problem with Configuration File \\n Unable to find required Configuration file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        else
                                            MessageBox.Show("Error connecting to the Server : \\n " + msg, "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    }
                                    finally
                                    {
                                        //conThread.Abort();                        
                                        //Console.WriteLine("Thread ISAlive = " + conThread.IsAlive);
                                    }                    
                                      
                                    Console.WriteLine("Execution Completed ");
                    

                    //**************

                        pri
                    
                    OriginalGriffO 1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      If your library is part of the same solution as your app, then they will both be Release or Debug together: Normally I have separate solutions, and issue the release version of a library for apps to use, while I continue changes in the debug version. In your case, that doesn't apply! If you mean that errorMsg remained empty after executing the code, could it be that the next line to be received (whether it is blank or not) starts off by setting errorMsg = ""; perhaps? Move your Console.WriteLine to immediately before the first if and see what happens.

                      Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                      A Offline
                      A Offline
                      All Time Programming
                      wrote on last edited by
                      #14

                      You see the code of StartConnect. I think and hence wanted to add StartConnect() in a thread and catch exceptions like that, but it didn't work out. Is it better to handle it in thread (the code that's commented) or as I have dneo is correct. If the commented is correct, then how to trap exceptions that are thrown by StartConnect or not to throw exceptions and handle them in that method only. Please guide me for this also. I am on this issue from last 3 days, on many trials couldn't suceed. Your points are helping to suceed. Thanks a lot. I highly appreciate it. Please keep helping on this issue and help me run the code normally to its and yours best.

                      Thanks & Regards,

                      OriginalGriffO 1 Reply Last reply
                      0
                      • A All Time Programming

                        Both are of different solutions. But yes, realized during debugging & removed the errorMsg = "" & connected = false lines. And now I see that errorMsg has value in it. Implementaion PART :

                                        try
                                        {
                                            //conThread = new Thread(new ThreadStart(StartConnect));
                                            //conThread.Start();
                                            StartConnect();
                                        }
                                        catch (ThreadAbortException te)
                                        {
                                            Console.WriteLine("Abort Exception CAUGHT");
                                        }
                                        catch (Exception ex)
                                        {
                                            string msg = ex.Message;
                                            if (msg.Equals("NotConnectedException"))
                                                MessageBox.Show("Error connecting to the Server : Connection Time Out \\n Unable to connect to the Server", "Time Out", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            else if (msg.IndexOf("Cannot load CA certificate file") > 0)
                                                MessageBox.Show("Error connecting to the Server : Problem with Certificate File \\n Unable to Load or Find required Certificate file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            else if (msg.IndexOf("Error opening 'Auth' auth file:") > 0)
                                                MessageBox.Show("Error connecting to the Server : Problem with Authentication File \\n Unable to Load or Find required Authentication file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            else if (msg.IndexOf("Error opening configuration file:") > 0)
                                                MessageBox.Show("Error connecting to the Server : Problem with Configuration File \\n Unable to find required Configuration file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            else
                                                MessageBox.Show("Error connecting to the Server : \\n " + msg, "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        }
                                        finally
                                        {
                                            //conThread.Abort();                        
                                            //Console.WriteLine("Thread ISAlive = " + conThread.IsAlive);
                                        }                    
                                          
                                        Console.WriteLine("Execution Completed ");
                        

                        //**************

                            pri
                        
                        OriginalGriffO Offline
                        OriginalGriffO Offline
                        OriginalGriff
                        wrote on last edited by
                        #15

                        Reply: it is. If it wasn't, then your output would contain the line: "THROWN" from the following statement. Best guess: You are swallowing or ignoring the exception at a higher level.

                        Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                        A 1 Reply Last reply
                        0
                        • A All Time Programming

                          You see the code of StartConnect. I think and hence wanted to add StartConnect() in a thread and catch exceptions like that, but it didn't work out. Is it better to handle it in thread (the code that's commented) or as I have dneo is correct. If the commented is correct, then how to trap exceptions that are thrown by StartConnect or not to throw exceptions and handle them in that method only. Please guide me for this also. I am on this issue from last 3 days, on many trials couldn't suceed. Your points are helping to suceed. Thanks a lot. I highly appreciate it. Please keep helping on this issue and help me run the code normally to its and yours best.

                          Thanks & Regards,

                          OriginalGriffO Offline
                          OriginalGriffO Offline
                          OriginalGriff
                          wrote on last edited by
                          #16

                          From looking briefly at your code, I think you first need to read up on threads before you try moving the code: you don't seem to understand what you are trying to do and the effects it has on execution. Read up first, and get your head round it. Then try it, and if you have problems, post a new question!

                          Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                          A 1 Reply Last reply
                          0
                          • OriginalGriffO OriginalGriff

                            Reply: it is. If it wasn't, then your output would contain the line: "THROWN" from the following statement. Best guess: You are swallowing or ignoring the exception at a higher level.

                            Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                            A Offline
                            A Offline
                            All Time Programming
                            wrote on last edited by
                            #17

                            YES, then it should have printed "THROWN". >> Best guess: You are swallowing or ignoring the exception at a higher level. Didn't get you. Can you please explain it or show proper guideline to modify accordingly.

                            Thanks & Regards,

                            1 Reply Last reply
                            0
                            • OriginalGriffO OriginalGriff

                              From looking briefly at your code, I think you first need to read up on threads before you try moving the code: you don't seem to understand what you are trying to do and the effects it has on execution. Read up first, and get your head round it. Then try it, and if you have problems, post a new question!

                              Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."

                              A Offline
                              A Offline
                              All Time Programming
                              wrote on last edited by
                              #18

                              Truly telling I read Threading tutorials of C#, but not getting such ways of threading. I mean calling method in it and such. I get threading of Java & C++ nicely, but C# can't get in mind properly. :~ If StartConnect is in a Thread, it cannot throw exceptions. If adding such type of code in a thread is best practice, then how to accomplish such activity as I have done. If I am wrong in my this thought, please tell me. Without putting in thread (the current situation), its working proper & also showing exception of cannot find file only. Thanks a lot for this. Please if you can help with the above also would be great. Atleast guide, I am not asking for written code. As said, this type of threading doesn't fit proeprly in my mind, so need assistance.

                              Thanks & Regards,

                              modified on Thursday, February 3, 2011 9:38 AM

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups