Solved

Obtain Exitcode from CMD using c#

Posted on 2010-09-17
9
830 Views
Last Modified: 2012-05-10
I am using following code to write the PATH, EXECUTABLE NAME and ARGUMENTS to a batch file and execute it through CMD using c#. The problem is sometimes the application dosent starts up after executing the batch file. And the c# code dosent give me exception or any notification.

For which i want to get the Exitcode from CMD to determine if the commands executed properly. How can i determine Exit code ?

script inside Batchfile : [Note that Notepads.exe is wrong to get the error ]

START Notepads.EXE

"if "%ERRORLEVEL%" == "1" exit /B 1"
public void Execute()
    {
        try
        {
            string LatestFileName = GetLastWrittenBatchFile();
            if (System.IO.File.Exists(BatchPath + LatestFileName))
            {
                System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
                procinfo.UseShellExecute = false;
                procinfo.RedirectStandardError = true;
                procinfo.RedirectStandardInput = true;
                procinfo.RedirectStandardOutput = true;

                System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo);

                System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName);
                System.IO.StreamReader sroutput = process.StandardOutput;
                System.IO.StreamWriter srinput = process.StandardInput;


                while (stream.Peek() != -1)
                {
                    srinput.WriteLine(stream.ReadLine());
                }

                Log.Flow_writeToLogFile("Executed .Bat file : " + LatestFileName);
                stream.Close();
                process.Close();
                srinput.Close();
                sroutput.Close(); 
                int iExitCode = process.ExitCode;
            }
            else
            {
                ExceptionHandler.writeToLogFile("File not found");
            }
        }
        catch (Exception ex)
        {
            ExceptionHandler.writeToLogFile(System.Environment.NewLine + "Target  :  " + ex.TargetSite.ToString() + System.Environment.NewLine + "Message :  " + ex.Message.ToString() + System.Environment.NewLine + "Stack   :  " + ex.StackTrace.ToString());
        }
    }

Open in new window

0
Comment
Question by:srk1982
  • 5
  • 4
9 Comments
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Subscribe to the event Exited event on the Process returned by Process.Start()  

 Process p = Process.Start(....);
p.Exited += new EventHandler(Process_Exited);

Process_Exited(object sender, eventargs e)
{
  Process p = sender as Process;
  p.ExitCode //this tell if there was an error or not
} Alternatively you can subscribte to ErrorDataReceived
0
 

Author Comment

by:srk1982
Comment Utility
@Dhaest, Pls tell me a solution with respect to my question. Because i am not starting a process directly from c# code.
I am writing the PATH, EXECUTABLE NAME and ARGUMENTS to a batch file and execute it through CMD using c#.
In this case, how can i get the error ?
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
It is much easier to run the process directly instead of using creating a batch file that you later execute since you lose some control since you are using a batch script layer
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Can you do it like this example ?
.NET Tip: Execute Commands From C#
http://www.developer.com/net/csharp/article.php/3707996/NET-Tip-Execute-Commands-From-C.htm
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:srk1982
Comment Utility
@Dhaest, What you said is absolutely correct. But i have to do it using batch file according to my requirement. They have a reason to use it. Kindly help me to do using batch file itself. Thanks.
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
I'm not sure if it's possible. The only thing I can think of right now, is too run the batch and output the exitcode to a file or something, which you can read in later in your program....

I don't think that I can help you further on this, because I would do it like I said earlier...
0
 

Author Comment

by:srk1982
Comment Utility
@:Dhaest The only thing I can think of right now, is too run the batch and output the exitcode to a file or something, which you can read in later in your program...."     This is what i want !!! It want to log the info.. Pls tell me how to do it...
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
You can add it on several ways in your bat-file.
Source: http://www.codeguru.com/forum/showthread.php?t=355047


Another usefull resource:
http://www.robvanderwoude.com/errorlevel.php

Sub AppendTextFile(FileNameDst, FileNameSrc)



  ' Copy a file at the end of another file

  

  Const ForReading = 1, ForWriting = 2, ForAppending = 8

  Dim fso, fDst, fSrc



  Set fso = CreateObject("Scripting.FileSystemObject")

  Set fDst = fso.OpenTextFile(FileNameDst, ForAppending,True)



  Set fSrc = fso.OpenTextFile(FileNameSrc, ForReading,True)

  Do Until fSrc.AtEndOfStream

    fDst.WriteLine fSrc.ReadLine

  Loop

  fSrc.Close



  fDst.Close



End Sub



Wscript.Echo "Starting appending files..."

Call AppendTextFile("test1.log", "test2.log")

Wscript.Echo "Done"

Open in new window

0
 

Accepted Solution

by:
srk1982 earned 0 total points
Comment Utility
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename);
                    psi.RedirectStandardOutput = true;
                    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    psi.UseShellExecute = false;
                    System.Diagnostics.Process listFiles;
                    listFiles = System.Diagnostics.Process.Start(psi);
                    System.IO.StreamReader myOutput = listFiles.StandardOutput;
                    listFiles.WaitForExit(2000);
                    if (listFiles.HasExited)
                    {
                        string output = myOutput.ReadToEnd();
                        MessageBox.Show(output);
                    }
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now