Solved

Obtain Exitcode from CMD using c#

Posted on 2010-09-17
9
866 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 33699234
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
ID: 33699323
@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
ID: 33699337
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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 53

Expert Comment

by:Dhaest
ID: 33699346
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
 

Author Comment

by:srk1982
ID: 33699353
@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
ID: 33699403
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
ID: 33699415
@: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
ID: 33699436
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
ID: 33713785
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

728 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