Solved

Obtain Exitcode from CMD using c#

Posted on 2010-09-17
9
858 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Expression Evaluater 3 46
insert value of checklistbox checked 4 39
I need help adding validation to my MVC.Net view 6 23
C# Windows app updating JSON file error. 9 39
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
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…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

726 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