C#

[C#]관리자 권한으로 프로그램 실행하기 예제

선영아 사랑해 2016. 9. 2. 13:29

특정 폴더 또는 파일에 접근 할 때 권한이 없어 UnauthorizedAccessException 때문에 고생하셨던 기억있으시죠?


프로젝트 생성 후 Program.cs 파일에서 추가하여 사용하면 됩니다.


프로그램 실행하면 관리자권한으로 사용할지 여부를 묻는 메시지박스 창에서 '예'를 선택하면 관리자 권한으로 프로그램을 사용 할 수 있습니다.


using System;
using System.Collections.Generic;
using System.Windows.Forms;


using System.Security.Principal;
using System.Diagnostics;


namespace WindowsApplication1
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (IsAdministrator() == false)
            {
                try
                {
                    ProcessStartInfo procInfo = new ProcessStartInfo();
                    procInfo.UseShellExecute = true;
                    procInfo.FileName = Application.ExecutablePath;
                    procInfo.WorkingDirectory = Environment.CurrentDirectory;
                    procInfo.Verb = "runas";
                    Process.Start(procInfo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();

            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }

            return false;
        }
    }
}