locked
Execute Shell/Command-line script from VB.NET RRS feed

  • Question

  • User951355356 posted

    Hi, I'm using the following code to execute a command-line script, which uses imagemagick (a third-party, free, image tool) to create a watermark.  (And then I run a similar command to attach the watermark to my image.)



    What I need, though, is to be able to receive the RESPONSE/RETURN CODE from the execution...cuz it seems to sometimes fail.

    Here's my code:

    Dim fileargs As String = "convert -size 300x200 xc:none -font Arial -pointsize 25 -kerning 1 -gravity center -fill black -annotate 330x330+0+0 ""Touchboards.com"" -fill white -annotate 330x330+2+2  ""Touchboards.com""  WATERMARK.png"
            Dim proc As New Diagnostics.Process()
            proc.StartInfo.Arguments = fileargs
            proc.StartInfo.FileName = Server.MapPath("/ProductMaintenance/Scripts/ImageMagick-6.7.1-Q16/convert.exe")
            proc.StartInfo.UseShellExecute = False
            proc.StartInfo.CreateNoWindow = True
            proc.StartInfo.RedirectStandardOutput = False
            proc.Start()

    So, this code usually works.  But once in a while, it seems to fail.  I'd really really like (NEED!) my vb.net code to know when it failed (and ideally the reason).

    Is there any way to do this?

    Thursday, July 28, 2011 12:38 PM

Answers

  • User-837620913 posted

    If ImageMagick writes to the StandardError stream (it should if it's a command-line program), you can grab the error output this way:

    // Start the child process.
     Process p = new Process();
     // Redirect the error stream of the child process.
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.FileName = "Write500Lines.exe";
     p.Start();
     // Do not wait for the child process to exit before
     // reading to the end of its redirected error stream.
     // p.WaitForExit();
     // Read the error stream first and then wait.
     string error = p.StandardError.ReadToEnd();
     p.WaitForExit();

    OR, if you just want the exit code, you can get that this way:

    myProcess = Process.Start("NotePad.exe");
    myProcess.WaitForExit(10000); // in milliseconds, so this is 10 seconds
    Console.WriteLine("Process exit code: {0}", myProcess.ExitCode);
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 29, 2011 6:33 AM