Development Tip

C # 관리자 권한으로 실행되는지 확인

yourdevel 2020. 12. 29. 08:03
반응형

C # 관리자 권한으로 실행되는지 확인


중복 가능성 :
현재 사용자가 관리자인지 확인

응용 프로그램 (C #으로 작성, OS Windows XP / Vista / 7 실행)이 관리자로 실행 중인지 테스트해야합니다 (예 : .exe-> 관리자 권한으로 실행 또는 속성 아래의 호환성 탭에서 관리자 권한으로 실행). .

Google을 검색하고 StackOverflow를 검색했지만 작동하는 솔루션을 찾을 수 없습니다.

내 마지막 시도는 다음과 같습니다.

if ((new WindowsPrincipal(WindowsIdentity.GetCurrent()))
         .IsInRole(WindowsBuiltInRole.Administrator))
{
    ...
}

이 시도

public static bool IsAdministrator()
{
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

이것은 기능적으로 코드와 동일하게 보이지만 위의 내용은 저에게 효과적입니다 ...

기능적으로 수행 (불필요한 임시 변수없이) ...

public static bool IsAdministrator()
{
   return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
             .IsInRole(WindowsBuiltInRole.Administrator);
}  

또는 표현식 본문 속성 사용 :

public static bool IsAdministrator =>
   new WindowsPrincipal(WindowsIdentity.GetCurrent())
       .IsInRole(WindowsBuiltInRole.Administrator);

참조 URL : https://stackoverflow.com/questions/11660184/c-sharp-check-if-run-as-administrator

반응형