Aller au contenu

Process

De Banane Atomic

Liens

Exécuter un fichier ou une commande

using System.Diagnostics;

// en une ligne
Process.Start("C:\chemin\fichier.exe", "paramètre1 paramètre2").WaitForExit();

// ProcessStartInfo?
Process.Start(new ProcessStartInfo("CheminVersLeFichier"));

// Avec des options
ProcessStartInfo psi = new ProcessStartInfo("exe", "paramètre1 paramètre2");
psi.WindowStyle = ProcessWindowStyle.Hidden; // masque le processus
Process proc = Process.Start(psi);
proc.WaitForExit(); // Attend que le processus se termine

// Lecture de la sortie
ProcessStartInfo psi = new ProcessStartInfo("/chemin/script.sh", "paramètre1 paramètre2");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
// par défaut, le working directory est celui de l'application appelante
// on peut donc le redéfinir pour qu'il corresponde au chemin du script appelé
psi.WorkingDirectory = Path.GetDirectoryName("/chemin/script.sh");
Process process = Process.Start(psi);
string processOutput = process.StandardOutput.ReadToEnd();
process.WaitForExit();

// écoute d'output et d'error
command = command.Replace("\"", "\\\"");
var process = new Process()
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "/bin/bash",
        Arguments = $"-c \"{command}\"",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true,
    }
};

process.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);
process.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);

process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();

process.WaitForExit();
Le WorkingDirectory du nouveau process sera le même que celui du process appelant et non le chemin vers l'exe du nouveau process.

Execute shell commands

Some shell commands rewrite on the current line, to keep the same visual as the original command, use {{{1}}}.

var processInfo = new ProcessStartInfo
{
    FileName = "borg",
    Arguments = $"create --verbose --progress --stats --compression lz4 \"{archive}\"::{{now:%Y-%m-%d}} {paths}",
    UseShellExecute = true,
    WorkingDirectory = "/path/folder"
};
processInfo.EnvironmentVariables["BORG_PASSPHRASE"] = borgPassword;

var process = new Process()
{
    StartInfo = processInfo
};

process.Start();
process.WaitForExit();

Lister tous les processus qui utilisent un fichier