728x90

C# 에서 관리자 권한으로 실행중인지 체크하는 코드다.

관리자 권한으로 실행중인지 알아야 할 때 이 코드를 활용하여 구현하면 도움이 될 거 같다.


using System;
using System.Security.Principal;


간단하게 작성하면

bool IsUserAdministrator(){
    WindowsIdentity user = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(user);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


좀 더 자세히 작성하면

public bool IsUserAdministrator()
{
    bool isAdmin;
    WindowsIdentity user = null;
    try
    {
        user = WindowsIdentity.GetCurrent(); // 현재 로그인된 user의 정보
        if (user == null)
            throw new InvalidOperationException("Couldn't get the current user identity");
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    finally
    {
        if (user != null)
            user.Dispose();
    }
    return isAdmin;
}

private void IsAdmin_Click(object sender, EventArgs e)
{
    if (IsUserAdministrator())
    {
        MessageBox.Show("관리자 권한으로 실행중입니다");
    }
    else
    {
        MessageBox.Show("관리자 권한으로 실행중이 아닙니다");
    }
}

블로그 이미지

Link2Me

,