Solved

Obtain Exitcode from CMD using c#

Posted on 2010-09-17
9
838 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
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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
XML & .net 5 41
Using C#, how could you improve upon my method of writing out a merged, compressed file? 2 34
Device Location 4 13
C# parent child form 5 19
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

895 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