LoginSignup
9
16

More than 3 years have passed since last update.

アプリケーションを管理者権限で起動する

Last updated at Posted at 2019-01-15

はじめに

アプリケーションを管理者権限で起動するにはマニフェストファイルに定義する方法もありますが, 実行ファイルのアイコンに盾マークが付いてしまいます. またデバッグ時にはVisual Studioのアクセス許可を引き上げる必要があります.

admin.png

そのため, 起動時に権限を確認し, 管理者権限でなければ管理者権限で再度起動することで実行ファイルに盾マークが付くことなく管理者権限起動することができるようになります.

権限の確認及び管理者権限で再起動

権限を確認し, 管理者権限でなければ別プロセスとして管理者権限を付与して起動し直します.

Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
var pri = (WindowsPrincipal)Thread.CurrentPrincipal;

//管理者権限以外での起動なら、別プロセスで本アプリを起動する
if (!pri.IsInRole(WindowsBuiltInRole.Administrator))
{
    var proc = new ProcessStartInfo()
    {
        WorkingDirectory = Environment.CurrentDirectory,
        FileName = Assembly.GetEntryAssembly().Location,
        Verb = "RunAs"
    };

    if (args.Length >= 1)
        proc.Arguments = string.Join(" ", args);

    //別プロセスで本アプリを起動する
    Process.Start(proc);

    //現在プロセス終了
    return;

}

上記処理をReleaseビルド時のみ有効とすることでVisual Studioでのデバッグ時は既存のプロセスのまま動作することとなりデバッグができることとなります.
以下, 全ソースとなります.

Program.cs
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {

#if (!DEBUG)
        Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        var pri = (WindowsPrincipal)Thread.CurrentPrincipal;

        //管理者権限以外での起動なら, 別プロセスで本アプリを起動する
        if (!pri.IsInRole(WindowsBuiltInRole.Administrator))
        {
            var proc = new ProcessStartInfo()
            {
                WorkingDirectory = Environment.CurrentDirectory,
                FileName = Assembly.GetEntryAssembly().Location,
                Verb = "RunAs"
            };

            if (args.Length >= 1)
                proc.Arguments = string.Join(" ", args);

            //別プロセスで本アプリを起動する
            Process.Start(proc);

            //現在プロセス終了
            return;

        }
#endif

        /* メインの処理 */

    }
}

最後に

起動時に管理者権限か確認し起動し直すことで, マニフェストファイルを使用することなく, アプリケーションを管理者権限で起動することができます.

9
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
16