Search code examples
c#child-processelevated-privileges

Making Processes inside C# to run as administrator


I made an app that removes virus shortcuts using attrib command in CMD, and I need administrator rights so I can make the command.

Currently I'm not able to do that neither by whole program nor the Process itself. Here's a piece of code that needs UAC:

private void Button2_Click(object sender, EventArgs e)
{
    string Disktype = null;
    Disktype = ListBox1.GetItemText(ListBox1.SelectedItem); ;
    if (Disktype.Contains("C:") == true)
    {
        MessageBox.Show("You selected C:");
    }
    else
    {
        String Message = "Cleaning" + Disk.Diskvolume + "Are you Sure?";
        String Title = "Cleaning now";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result = MessageBox.Show(Message, Title, buttons);
        if (result == DialogResult.Yes)
        {
            String ShowFiles = "attrib -h -r -s /s /d" + Disktype + "*.*";
            String RemoveVirus = "del" + Disktype + "*.lnk";
            System.Diagnostics.Process.Start("CMD.exe", ShowFiles);
            System.Diagnostics.Process.Start("CMD.exe", RemoveVirus);
            MessageBox.Show("Cleaning");
            System.Diagnostics.Process.Start(Disktype);
            Close();
        }
        else
        {
            MessageBox.Show("Cleaning done");
            Close();
        }
    }

As you can see, I made ShowFiles and RemoveVirus directly to the cmd, but I'm having trouble as to how make them run as administrator.

Do I need it for the whole C# application or just the Process.Start ones?


Solution

  • i was looking and you can try this:

    string command;
    command = "powershell -Command 'Start-Process cmd -Verb RunAs'"
    System.Diagnostics.Process.Start("cmd.exe",command);
    

    You can start CMD as Admin just using powershell.

    Using this you can use the commands without problems.

    I hope it works for you :)