?
Solved

Obtain Exitcode from CMD using c#

Posted on 2010-09-17
9
Medium Priority
?
870 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
Independent Software Vendors: 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

Independent Software Vendors: 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!

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
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…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

800 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