Search code examples
c++winapibatch-fileadminelevated-privileges

How do I check if my program is running under admin privileges via C++?


How do I check if my C++ program is running with admin privileges?

I did it in this manner for batch

set fold=%random%

mkdir "C:\Windows\%fold%"

if errorlevel 1 (

goto Tag1

)

goto Tag2

But I cannot use the same thing for C++ because I do not know how to transfer value of %random% that is variable 1 to variable 2 that is %fold% and also, I do not know if there is error level for C++.

Can anyone help me in this case or is there any way to check if my program is running with admin privileges?


Solution

  • You can use the OpenProcessToken / GetTokenInformation pair: https://stackoverflow.com/a/8196291/3235496

    An alternative is the AccessCheck function.

    Last the IsUserAnAdmin function: it's simple but deprecated (available from Windows XP/Windows Server 2003).

    Anyway why are you checking? Trying could be a good strategy: if it works, you have sufficient rights (possibly a subset of Admin rights).

    PS

    Just out of curiosity... the C++ translation of your batch file should be based on the CreateDirectory function. If it fails check the extended error information via GetLastError (return code ERROR_ACCESS_DENIED). But, as David Heffernan says, spraying folders into the system directories isn't a great idea.