I would like to display some extra UI elements when the process is being run as Administrator as opposed to when it isn't, similar to how Visual Studio 2008 displays 'Administrator' in its title bar when running as admin. How can I tell?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I think this is a good simple mechanism.
I felt it important to note the difficulty I had with attempting to use WellKnownSidType.BuiltinAdministratorsSid per casperOne's answer above. According to the WellKnownSiDType MSDN, BuiltinAdministratorsSid "Indicates a SID that matches the administrator account." So I would expect casperOne's code to work, and guess it likely does in some environments. Unfortunately, it didn't on my Windows 2003 with .NET 2.0 (legacy code). It actually returned S-1-5-32-544 which, according to this article is the sid for the Administrators group. Thus, the comparison fails for me. I will have to do my own string comparison for startswith "S-1-5-21" (that kb 243330 indicates the "21" is included even though the blog referenced above does not) and endswith "500".
Technically, if you want to see if the member is the local administrator account, then you can get the security identifier (SID) of the current user through the
User
property on theWindowsIdentity
class, like so (the staticGetCurrent
method gets the current Windows user):The
User
property returns the SID of the user which has a number of predefined values for various groups and users.Then you would check to see if the SID has the following pattern, indicating it is the local administrator account (which is a well-known SID):
Or, if you don't want to parse strings, you can use the
SecurityIdentifier
class:However, I suspect that what you really want to know is if the current user is a member of the administrators group for the local machine. You can get this SID using the
WellKnownSidType
ofBuiltinAdministratorsSid
:Then you can check the
Groups
property on theWindowsIdentity
of the user to see if that user is a member of the local admin group, like so:Here's a one liner to do it.