앙큼한 개발기록

[c#] 프로그램 시작시 관리자권한 본문

개발

[c#] 프로그램 시작시 관리자권한

angkeum 2023. 5. 23. 12:30

프로젝트에서 관리자 권한이 필요한 경우가 있다. 

관리자 권한을 부여하는 방법은 2가지가 있다. 

 

1. 프로그램에서 관리자 권한을 요청하여 수락하는경우 

2. 프로젝트 자체를 관리자 권한으로 실행하도록 하는 경우 

 

관리자 권한을 요청하는 경우에는 

프로그램을 시작할때 프로세스를 띄워 

권한을 수령하고 시작하는 방법이다

 

Program.cs

    internal 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.ToString());
                }

                return;
            }

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            catch (Exception ex)
            {
                MessageBox.Show($"시스탬을 재시작하지 못했습니다 \r\n {ex}", "에러");
            }
        }

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

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

            return false;
        }
    }

 

2. 프로젝트 자체를 관리자 권한으로 등록하는 경우

 

비주얼스튜디오에서 application manifest file을 추가 한다. 

- 매니페스트 파일을 추가하는 방법은 솔루션에서 바로 추가 하거나 

 

 

- 프로젝트의 속성에서 Click once 보안 설정 사용을 클릭 후 해제하면 파일이 생성된다. 

 

 

해당 파일을 자세히 보면

주석으로 친절하게 requestedExecutionLevel 속성을 변경하면 프로젝트 권한이 바뀐다고 적혀 있다. 

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC 매니페스트 옵션
             Windows 사용자 계정 컨트롤 수준을 변경하려면 
             requestedExecutionLevel 노드를 다음 중 하나로 바꿉니다.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            requestedExecutionLevel 요소를 지정하면 파일 및 레지스트리 가상화를 사용하지 않습니다. 
            이전 버전과의 호환성을 위해 애플리케이션에 가상화가 필요한 경우
            이 요소를 제거합니다.
        -->
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
      <applicationRequestMinimum>
        <defaultAssemblyRequest permissionSetReference="Custom" />
        <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
      </applicationRequestMinimum>
    </security>
  </trustInfo>
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- 이 애플리케이션이 테스트되고 함께 작동하도록 설계된 Windows 버전
           목록입니다. 해당 요소의 주석 처리를 제거하면 Windows에서
           호환 가능성이 가장 큰 환경을 자동으로 선택합니다. -->
      <!-- Windows Vista -->
      <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
      <!-- Windows 7 -->
      <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
      <!-- Windows 8 -->
      <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
      <!-- Windows 8.1 -->
      <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
      <!-- Windows 10 -->
      <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
    </application>
  </compatibility>
  <!-- 애플리케이션이 DPI를 인식하며 높은 DPI에서 Windows가 자동으로 스케일링하지
       않음을 나타냅니다. WPF(Windows Presentation Foundation) 애플리케이션은 자동으로 DPI를 인식하며 
       옵트인할 필요가 없습니다. 이 설정에 옵트인한 .NET Framework 4.6을 대상으로 하는 
       Windows Forms 애플리케이션은 app.config에서 'EnableWindowsFormsHighDpiAutoResizing' 설정도 'true'로 설정해야 합니다. 
       
       애플리케이션이 긴 경로를 인식하도록 설정합니다. https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation을 참조하세요. -->
  <!--
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
      <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
    </windowsSettings>
  </application>
  -->
  <!-- Windows 공용 컨트롤 및 대화 상자의 테마 사용(Windows XP 이상) -->
  <!--
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
          type="win32"
          name="Microsoft.Windows.Common-Controls"
          version="6.0.0.0"
          processorArchitecture="*"
          publicKeyToken="6595b64144ccf1df"
          language="*"
        />
    </dependentAssembly>
  </dependency>
  -->
</assembly>

 

 

requestedExecutionLevel 을 "requireAdministrator"로 변경하면 

프로젝트 자체가 관리자 권한으로만 실행하게 된다.

Comments