Lancer une tâche avec les droits maximaux en C#

barale61 Messages postés 1214 Date d'inscription   Statut Membre Dernière intervention   -  

Bonjour,

Je n'arrive pas à lancer une tâche qui doit s'exécuter avec les droits maximaux à partir de mon application en C# démarrée en administrateur.

Je vous remercie pour votre aide.

Pourtant quand je saisi la commande dans un terminal, cela fonctionne bien : 

SCHTASKS /CREATE /F /TN "BackupManager\Profile3" /TR "\"D:\Projects_VS\_BackupManager\BackupManager\bin\Debug\net8.0-windows\BackupManager.exe\" --run-backup \"Profile3\"" /SC DAILY /ST 16:56 /RL HIGHEST /RU SYSTEM

 Résultat dans le terminal en administrateur : 

Résultat avec mon application :


Voici mon code : 

public void CreateOrUpdateTask(BackupProfile profile)
{
    if (!profile.IsScheduleEnabled || !profile.NextScheduledBackup.HasValue)
        return;

    string folderPath = "BackupManager";
    string taskName = $"{folderPath}\\{profile.Name}";
    string appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    string arguments = $"--run-backup \"{profile.Name}\"";

    // Créer le dossier s'il n'existe pas
    using (TaskService ts = new TaskService())
    {
        if (!ts.RootFolder.SubFolders.Exists(folderPath))
        {
            ts.RootFolder.CreateFolder(folderPath);
        }
    }

    // Formater la date et l'heure pour SCHTASKS
    DateTime startTime = profile.NextScheduledBackup.Value;
    string scheduledTime = startTime.ToString("HH:mm");
    string scheduledDate = startTime.ToString("dd/MM/yyyy");

    // Construire la commande SCHTASKS selon le type de planification
    string scheduleType;
    string interval = "";

    switch (profile.ScheduleType)
    {
        case BackupScheduleType.UneFois:
            scheduleType = "ONCE";
            break;
        case BackupScheduleType.Quotidien:
            scheduleType = "DAILY";
            interval = $"/MO {profile.ScheduleInterval}";
            break;
        case BackupScheduleType.Hebdomadaire:
            scheduleType = "WEEKLY";
            string dayOfWeek = startTime.DayOfWeek.ToString().ToUpper().Substring(0, 3);
            interval = $"/D {dayOfWeek} /MO {profile.ScheduleInterval}";
            break;
        case BackupScheduleType.Mensuel:
            scheduleType = "MONTHLY";
            int day = startTime.Day;
            interval = $"/D {day} /MO {profile.ScheduleInterval}";
            break;
        case BackupScheduleType.Horaire:
            scheduleType = "HOURLY";
            interval = $"/MO {profile.ScheduleInterval}";
            break;
        default:
            scheduleType = "ONCE";
            break;
    }

    // Créer la commande complète
    // /RL HIGHEST : Exécuter avec les privilèges les plus élevés
    // /RU SYSTEM : Exécuter en tant que SYSTEM (pas besoin de connexion utilisateur)
    string schtasksCmd = $"SCHTASKS /CREATE /F /TN \"{taskName}\" /TR \"\\\"{appPath}\\\" {arguments}\" /SC {scheduleType} {interval} /SD {scheduledDate} /ST {scheduledTime} /RL HIGHEST /RU SYSTEM";

    System.Diagnostics.Debug.WriteLine($"Commande SCHTASKS: {schtasksCmd}");
    try
    {
        // Exécuter la commande
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = "schtasks.exe", // Exécution directe de SCHTASKS
            Arguments = $"/CREATE /F /TN \"{taskName}\" /TR \"\\\"{appPath}\\\" {arguments}\" /SC {scheduleType} {interval} /SD {scheduledDate} /ST {scheduledTime} /RL HIGHEST /RU SYSTEM",
            UseShellExecute = false, // Nécessaire pour rediriger la sortie
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        using (Process process = Process.Start(psi))
        {
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            System.Diagnostics.Debug.WriteLine($"SCHTASKS Output: {output}");
            System.Diagnostics.Debug.WriteLine($"SCHTASKS Error: {error}");

            if (process.ExitCode == 0)
            {
                System.Diagnostics.Debug.WriteLine($"Tâche créée avec succès: {taskName}");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"Erreur lors de la création de la tâche. Code de sortie: {process.ExitCode}");
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine($"Exception lors de la création de la tâche: {ex.Message}");
    }
}