ShellExecute and Execute file in C#

ShellExecute is used to open files using the appropriate program.
To open a pdf file, usually will be used Acrobat Reader, but we don’t know the program the user had associated to the file extension/mine type.

So the solution in C++ was use ShellExecute.
In C# the same process will be achieved using this code:

public static System.Diagnostics.Process Execute(string path)
{
    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(path);

    info.RedirectStandardError = false;
    info.RedirectStandardOutput = false;
    info.UseShellExecute = true;

    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = info;

    p.Start();

    return p;
}

To open an Executable file (.exe, .bat ecc) and obtain the standardError or StandardOutput use this code:

public static System.Diagnostics.Process Execute(string path)
{
    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(path);

    info.RedirectStandardError = true;
    info.RedirectStandardOutput = true;
    info.UseShellExecute = false;

    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = info;

    p.Start();

    return p;
}

and here an example to use it

StringBuilder sbError = new StringBuilder();
StringBuilder sbOutput = new StringBuilder();

Execute("myfile.exe");

process.WaitForExit();

if (process.ExitCode != 0) // error occured
{
    // read the std error
    while (!process.HasExited || !process.StandardError.EndOfStream)
        sbError.Append(process.StandardError.ReadToEnd());
}
else
{
    // read the std Output
    while (!process.HasExited || !process.StandardOutput.EndOfStream)
        sbOutput.Append(process.StandardOutput.ReadToEnd());
}
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in .Net, c# e contrassegnata con , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...