반응형

C# 콘솔 프로그램을 관리자 권한으로 실행하도록 해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Diagnostics;
using System.Security.Principal;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAdministrator();
 
            Console.WriteLine("관리자 권한으로 실행 중.");
            Console.ReadLine();
        }
 
        static void RunAdministrator()
        {
            if (!IsAdministrator())
            {
                try
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo()
                    {
                        UseShellExecute = true,
                        FileName = System.Reflection.Assembly.GetEntryAssembly().Location,
                        //FileName = System.Reflection.Assembly.GetExecutingAssembly().Location,
                        WorkingDirectory = Environment.CurrentDirectory,
                        Verb = "runas"
                    };
                    //processStartInfo.UseShellExecute = true;
                    //processStartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
                    //processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
                    //processStartInfo.Verb = "runas";
 
                    Process.Start(processStartInfo); // 관리자 권한으로 다시 실행.
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + ": 이 프로그램은 관리자 권한으로 실행해야 합니다.");
                    Console.Read();
 
                    Environment.Exit(0);
                }
 
                Console.WriteLine("관리자 권한으로 다시 실행 완료.");
                Console.ReadLine();
 
                Environment.Exit(0);
            }
        }
 
        static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
 
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
 
            return false;
        }
    }
}
 

 

소스를 입력하고 빌드한다. 프로그램을 실행하면 사용자 계정 컨트롤 화면이 나오고 앱의 디바이스 변경 허용 여부를 묻는다.

 

디바이스 변경을 허용 하면 위와 같은 메세지가 나온다.

 

관리자 권한으로 다시 실행된 프로그램.

 

디바이스 변경을 거부하면 위와 같은 메세지가 나오고 종료된다.

 

 

윈폼의 경우 Main()가 있는 Program.cs파일을 아래와 같이 수정한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Security.Principal;
using System.Diagnostics;
 
namespace WindowsFormsApp1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!IsAdministrator())
            {
                try
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo()
                    {
                        UseShellExecute = true,
                        FileName = Application.ExecutablePath,
                        WorkingDirectory = Environment.CurrentDirectory,
                        Verb = "runas"
                    };
                    //processStartInfo.UseShellExecute = true;
                    //processStartInfo.FileName = Application.ExecutablePath,;
                    //processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
                    //processStartInfo.Verb = "runas";
 
                    Process.Start(processStartInfo); // 관리자 권한으로 다시 실행 후 이 프로그램은 종료.
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message + ": 이 프로그램은 관리자 권한으로 실행해야 합니다.");
                }
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
 
        static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
 
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
 
            return false;
        }
    }
}
 

 

 

반응형
Posted by J-sean
: