开发者

How to know if Process.Start() is successful?

I've tried two different methods for starting a process.

The first

The definition is defined as parameters to the Start method:

System.Diagnostics.Process.Start("excel", string.Format("\"{0}\"", ExcelFileBox.Text.ToString()));

My thoughts:

This one starts just fine, but I don't know how to get feedback from it.

The second

I started looking into ProcessStartInfo because I want to know if Excel started successfully or not--for instance, while it's very likely it exists on the user's machine, there's no guarantee and it would be silly for me to indicate to the user that it's started successfully when it hasn't.

System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo
{
    FileName = "excel",
    Arguments = string.Format("\"{0}\"", ExcelFileBox.Text.ToString()),
    ErrorDialog = true,
    UseShellExecute = false,
    WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};

try
{
    System.Diagnostics.Process.Start(startinfo);
}
catch (Exception err)
{
    Console.WriteLine(err.Message);
}

My thoughts:

This gives the error: "The system cannot find the file specified", but it's unclear whether it means the Excel application or my file. In any case, while I appreciate the error message ability, I shouldn't be receiving out at the moment.

Thought, suggestions, ideas on how t开发者_运维百科o know if this happened successfully?

Solved

I put the first way of starting a process into a try-catch and it works beautifully.


The MSDN page on Process.Start() states that this method has an overload of type Boolean, where the return values mean:

true if a process resource is started; false if no new process resource is started (for example, if an existing process is reused).

Additionally it can throw three exceptions:

  • InvalidOperationException

No file name was specified in the Process component's StartInfo.

-or-

The ProcessStartInfo.UseShellExecute member of the StartInfo property is true while ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true.

  • Win32Exception

There was an error in opening the associated file.

  • ObjectDisposedException

The process object has already been disposed.


To use this overload of Process.Start() (which is the only non static overload of the method) you need to create an instance of the Process class using a ProcessStartInfo object.

An example of this is below:

ProcessStartInfo processStartInfo = new ProcessStartInfo("EXCEL.EXE");

Process process = new Process();
process.StartInfo = processStartInfo;
if (!process.Start())
{
    // That didn't work
}

Though, given that this can still throw you are probably better of just wrapping a catch around one of the static .Start() method calls.


Given that, it seems clear that the call to Process.Start() will either work or not and you can determine this from the return value being 0 (or an exception being thrown).

Once your process has started you then have a lot of control over things, with properties of the Process class such as HasExited allowing you to check what state the process is in.

In short - if the user does not have excel on their machine, Process.Start() will throw an exception.


You can check the Process.ExitCode property for a 0 (success) value .


Process.Start() also returns a boolean value that let's you know if it acquired an existing process or if a new process was started.

Furthermore, you can check the ProcessId of the process to ensure it's started/still running. Something like:

bool started = False;
Process p = new Process();
p.StartInfo = YourStartInfo;
started = p.Start();

try {
  int procId = p.Id;
}
catch(InvalidOperationException){
  started = False
}
catch(Exception ex) {
  started = False
}


To accurately determine if the process actually started, I tried to find the process id, if it found the process id it would continue if it couldn't find the process id it would enter the catch and print a debug statement.

try
{
     bool pathExists = File.Exists(module.ExecutionPath);
     if (pathExists)
     {
         ProcessStartInfo startArgs = new ProcessStartInfo();
         startArgs.FileName = "C:\Windows\System32\notepad.exe";
         startArgs.Arguments = null;
           
         Process process = new Process();
         process.StartInfo = startArgs;
         process.Start();
            
        Process startedProcess = CheckIfProcessStarted(process);
     }
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message + "  " + ex.InnerException);
    Debug.WriteLine("Couldnt find the process so it never ran");
}
        
private Process CheckIfProcessStarted(Process process)
{
    return Process.GetProcessById(process.Id);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜