始终使用提升的权限

时间:2015-08-29 14:52:44

标签: c# winforms permissions visual-studio-2015

我有一个winform应用程序,在Program.cs中包含以下代码,以确保我的应用程序始终以管理权限运行:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // Init visual styles
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Check if app is launched with administrative privilage
        WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);

        // Check if application is already running
        bool mutexCheck;
        var mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetType().GUID.ToString(), out mutexCheck);
        if (!mutexCheck)
        {
            // Error
            Utils.ShowError("Program is already running.");
            return;
        }

        // If app is running without administrative privilage
        if (!administrativeMode)
        {
            // Request administrative privilage
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.Verb = "runas";
            startInfo.FileName = Application.ExecutablePath;
            try
            {
                // Run app as administrator
                Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                // Error
                Utils.ShowError("Program failed to start - " + ex.Message);
                return;
            }
        }
        return;

        // Launch application
        Application.Run(new MyApp());
        GC.KeepAlive(mutex);
    }
}

每次我按F5在Visual Studio 2015中以调试模式运行应用程序时,应用程序似乎刚刚运行 - 调试环境未启动。

所以,我要做的就是转到Debug -> Attach to Process...并选择MyApp.exe,然后系统会提示我:

enter image description here

然后当我点击Restart under different credentials时 - VS2015重启。然后,我将关闭已经运行的MyApp实例,然后按F5以使用提升的权限重新启动;当我这样做 - 调试工作。

有没有办法将我的VS2015设置为始终以提升的权限运行此项目?

1 个答案:

答案 0 :(得分:2)

尝试以管理员身份运行Visual Studio。在我遇到权限不足的情况下运行Visual Studio以管理员身份修复了我的问题。