Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.IO;
- namespace ...
- {
- class Task
- {
- public string TaskName;
- public string FileName;
- public enum Trigger
- {
- atLogon,
- atStartup,
- atCreation
- }
- public Task()
- {
- if (!isAdmin())
- {
- throw new UnauthorizedAccessException("The user is currently not an admin so tasks cannot be managed");
- }
- }
- public bool isAdmin()
- {
- bool admin = false;
- string testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "_.txt");
- try
- {
- File.Create(testFile);
- if (File.Exists(testFile))
- {
- admin = true;
- File.Delete(testFile);
- return admin;
- }
- }
- catch
- {
- }
- return admin;
- }
- public bool checkExists()
- {
- ProcessStartInfo start = new ProcessStartInfo();
- start.FileName = "schtasks.exe";
- start.UseShellExecute = false;
- start.CreateNoWindow = true;
- start.WindowStyle = ProcessWindowStyle.Hidden;
- start.Arguments = "/query /TN \"" + TaskName + "\"";
- start.RedirectStandardOutput = true;
- using (Process process = Process.Start(start))
- {
- using (StreamReader reader = process.StandardOutput)
- {
- string stdout = reader.ReadToEnd();
- if (stdout.Contains(TaskName))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- }
- public bool createTask(Trigger t)
- {
- string tt = "";
- switch (t)
- {
- case Trigger.atLogon:
- tt = "ONLOGON";
- break;
- case Trigger.atCreation:
- tt = "ONCE";
- break;
- case Trigger.atStartup:
- tt = "ONSTARTUP";
- break;
- }
- return runCMD("schtasks /create /ru \"SYSTEM\" /sc " + tt + " /tn \"" + TaskName + "\" /tr \"" + FileName + "\" /rl HIGHEST /f");
- }
- public bool disableTask()
- {
- return runCMD("schtasks /change /tn \"" + TaskName + "\" /disable");
- }
- public bool enableTask()
- {
- return runCMD("schtasks /change /tn \"" + TaskName + "\" /enable");
- }
- public bool deleteTask()
- {
- return runCMD("schtasks /delete \"" + TaskName + "\"");
- }
- public bool runTask()
- {
- return runCMD("schtasks /run \"" + TaskName + "\"");
- }
- private bool runCMD(string command, bool asAdmin = true)
- {
- try
- {
- Process.Start(
- new ProcessStartInfo()
- {
- FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\cmd.exe",
- Verb = asAdmin ? "runas" : "",
- Arguments = "/c " + command,
- WindowStyle = ProcessWindowStyle.Hidden
- }
- );
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement