How to force my C# Winforms program run as administrator on any computer?

前端 未结 5 1118
失恋的感觉
失恋的感觉 2020-11-29 04:52

How to force my C# Winforms program run as administrator on any computer ? and any kind of OS ?

I need code solution (any sample code will be excell

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 05:47

    Here is the sample code to run your application as admin.

    ProcessStartInfo proc = new ProcessStartInfo();
    proc.UseShellExecute = true;
    proc.WorkingDirectory = Environment.CurrentDirectory;
    proc.FileName = Application.ExecutablePath;
    proc.Verb = "runas";
    try
    {
        Process.Start(proc);
    }
    catch
    {
        // The user refused the elevation.
        // Do nothing and return directly ...
        return;
    }
    Application.Exit();  // Quit itself
    

    Set the ProcessStartInfo.Verb to “runas” will let it run as admin. Here is related FAQ

    http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/28f84724-af3e-4fa1-bd86-b0d1499eaefa#x_FAQAnswer91

提交回复
热议问题