Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否将用户名转换为WindowsIdentity?_C#_.net_Vb.net_Admin_User Accounts - Fatal编程技术网

C# 是否将用户名转换为WindowsIdentity?

C# 是否将用户名转换为WindowsIdentity?,c#,.net,vb.net,admin,user-accounts,C#,.net,Vb.net,Admin,User Accounts,我用C来标记这个问题,因为它是.NET的一部分,并且众所周知,有些人可以毫无问题地编程和理解VB.NET和C作为一个整体,如果我能将C#指令翻译成VB.NET的话,我会很乐意使用其中一种语言编写解决方案。 我想在这个函数中指定一个用户名来检索,如果它是管理员还是非管理员,我应该做什么更改 MsgBox(UserIsAdmin("Elektro")) ' ByVal UserName as String or other needed object. Public Function UserI

我用
C
来标记这个问题,因为它是
.NET
的一部分,并且众所周知,有些人可以毫无问题地编程和理解
VB.NET
C
作为一个整体,如果我能将
C#
指令翻译成
VB.NET
的话,我会很乐意使用其中一种语言编写解决方案。


我想在这个函数中指定一个用户名来检索,如果它是管理员还是非管理员,我应该做什么更改

MsgBox(UserIsAdmin("Elektro"))

' ByVal UserName as String or other needed object.
Public Function UserIsAdmin(ByVal UserName As XXXX) As Boolean 

    Dim Identity As Security.Principal.WindowsIdentity =
    Security.Principal.WindowsIdentity.FromUserName(UserName)

    Return New Security.Principal.WindowsPrincipal(Identity).
               IsInRole(Security.Principal.WindowsBuiltInRole.Administrator)

End Function
PS:当然,
FromUserName
方法不存在


更新

我只是在尝试@meziantou方法,但我总是会遇到一个关于用户名结构或网络条目的异常,但是,无论如何,这并不是我想要的(我的意思是指定一个域名或计算机名或其他任何不是由函数自动完成的)


要从用户名中获取
WindowsIdentity
,可以使用
WindowsIdentity
构造函数()

您可以使用检索属于管理员组的所有用户。拥有所有成员后,您可以通过将该成员的名称与提供的用户名进行比较来确定该用户是否在组中

例如:

Public Function UserIsAdmin(ByVal userName As String) As Boolean
        Dim groupName As String = "administrators" '<--You can localize this'
        Dim isAdmin As Boolean
        Using context As PrincipalContext = New PrincipalContext(ContextType.Machine)
            Dim gfilter As GroupPrincipal = GroupPrincipal.FindByIdentity(context, groupName)
            If gfilter IsNot Nothing Then
                Dim members = gfilter.GetMembers
                For Each member In members
                    If String.Compare(member.Name, userName, True) = 0 Then
                        isAdmin = True
                    End If
                Next
            End If
        End Using
        Return isAdmin
End Function
公共函数UserIsAdmin(ByVal用户名作为字符串)作为布尔值

Dim groupName As String=“administrators”MSDN说,
WindowsIdentity
对象只能是已登录的用户,因此似乎无法进行我想要的用户名转换,但这是一个可行的解决方案:

' User Is Admin?
'
' Instructions:
' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
' 2. Imports System.DirectoryServices.AccountManagement
'
' Example Usages:
' MsgBox(UserIsAdmin("Administrador"))
' MsgBox(UserIsAdmin(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500")))
'
''' <summary>
''' Determines whether an User is an Administrator, in the current machine.
''' </summary>
''' <param name="UserName">Indicates the account Username.</param>
''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
Public Function UserIsAdmin(ByVal UserName As String) As Boolean

    Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")

    Dim pContext As New PrincipalContext(ContextType.Machine)
    Dim pUser As New UserPrincipal(pContext)
    Dim pSearcher As New PrincipalSearcher(pUser)

    Dim User As Principal =
        (From u As Principal In pSearcher.FindAll
        Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

    If User Is Nothing Then
        Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
    End If

    Dim IsAdmin As Boolean =
        (From Group As GroupPrincipal In User.GetGroups
         Where Group.Sid = AdminGroupSID).Any

    pContext.Dispose()
    pSearcher.Dispose()
    pUser.Dispose()

    Return IsAdmin

End Function
“用户是管理员吗?”?
'
“说明:
' 1. 添加对“System.DirectoryServices.AccountManagement”的引用。
' 2. 导入System.DirectoryServices.AccountManagement
'
'示例用法:
'MsgBox(UserIsAdmin(“管理员”))
'MsgBox(UserIsAdmin(新的Security.Principal.SecurityIdentifier(“S-1-5-21-250596608-219436059-1115792336-500”))
'
''' 
''确定用户是否是当前计算机中的管理员。
''' 
''表示帐户用户名。
''如果用户是管理员,则为true,否则为false。
作为布尔值的公共函数UserIsAdmin(ByVal用户名作为字符串)
Dim AdminGroupSID作为新的安全标识符(“S-1-5-32-544”)
Dim pContext作为新的PrincipalContext(ContextType.Machine)
Dim pUser作为新用户主体(pContext)
Dim pSearcher作为新的PrincipalSearcher(pUser)
Dim用户作为主体=
(来自美国,作为pSearcher.FindAll的负责人
其中u.Name.Equals(UserName,StringComparison.OrdinalIgnoreCase)).FirstOrDefault
如果用户什么都不是,那么
抛出新异常(String.Format(“未找到名为“{0}”的用户。”,用户名))
如果结束
Dim IsAdmin为布尔型=
(作为User.GetGroups中的GroupPrincipal从组中)
其中Group.Sid=AdminGroupSID)。任何
pContext.Dispose()
pSearcher.Dispose()
pUser.Dispose()
返回IsAdmin
端函数

谢谢,但在我的情况下,它抛出了一个例外,它说提供的名称不是具有适当结构的帐户名,因此我还尝试指定域,如
UserIsAdmin(“MyPCName\MyUserName”)
但仍会引发异常,但无论如何,如果引发异常,因为我只想在方法参数上指定用户名,而不是域名。构造函数表示重载需要一个
用户主体名称(UPN)字符串,而不仅仅是用户名,我将澄清,我的意图只是将用户名传递给该方法,以便该方法能够解析域,无论如何,我尝试传递UPN字符串却没有成功(这是我第一次尝试):
UserIsAdmin(“Administrador@127.0.0.1“”
此示例适用于我的机器,也许因为我的机器是一个域名的成员,你应该考虑使用PrimPaltSeC取取器检索所有主要对象的集合(使用PrimalSalpChur.FindAll),从那里确定哪个主体具有你正在寻找的身份。(PrincipalSearcher信息:)(FindAll信息:)@Frinavale谢谢,但我找不到适应它的方法。我试图将搜索者的名称传递给函数,但仍然表示名称不正确。因此,我尝试直接在搜索器中检查用户是否是管理员,获取groups
GetGroups
方法,但我看到的是
Administrators
组的名称取决于语言,因此在我的语言中,名称完全不同,然后比较名称是无效的。我能做什么?如果您愿意,请查看我的最新问题。谢谢这里必须有一个方法来解决这个本地化问题。“IsInRole”方法使用字符串,因此不要使用WindowsBuiltInRole.Administrator,请尝试传入“Administrator”(当然,我假设“Administrator”是以英语存储的……如果不是,则必须使用资源来正确地本地化该词,以使其匹配)我不知道如何正确地本地化Administrators组的名称,MSDN url似乎没有关于我的问题的信息,您能举个例子吗?我需要这个“UserIsAdmin”作为通用的解决方案。在我们开始讨论全球化这个大主题之前,上面的函数对你有用吗?如果没有,您是否尝试设置
groupName=“Administradors”
?那有用吗?上述代码适用于我,但我在Windows 7操作系统上使用的是美国英语文化,听起来您在系统上使用的是西班牙语文化,将“Administrators”翻译为“Administrators”,您需要对此进行补偿。不,您的代码应仅适用于美国语言(“Administrators”),根据您关于
Principal
GroupPrincipal
用法的建议,并做了更多的研究,我发现了另一种方法,只是比较组的SID,我
Dim windowsIdentity = New WindowsIdentity("administrator")
New WindowsPrincipal(windowsIdentity).IsInRole(WindowsBuiltInRole.Administrator)
Public Function UserIsAdmin(ByVal userName As String) As Boolean
        Dim groupName As String = "administrators" '<--You can localize this'
        Dim isAdmin As Boolean
        Using context As PrincipalContext = New PrincipalContext(ContextType.Machine)
            Dim gfilter As GroupPrincipal = GroupPrincipal.FindByIdentity(context, groupName)
            If gfilter IsNot Nothing Then
                Dim members = gfilter.GetMembers
                For Each member In members
                    If String.Compare(member.Name, userName, True) = 0 Then
                        isAdmin = True
                    End If
                Next
            End If
        End Using
        Return isAdmin
End Function
' User Is Admin?
'
' Instructions:
' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
' 2. Imports System.DirectoryServices.AccountManagement
'
' Example Usages:
' MsgBox(UserIsAdmin("Administrador"))
' MsgBox(UserIsAdmin(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500")))
'
''' <summary>
''' Determines whether an User is an Administrator, in the current machine.
''' </summary>
''' <param name="UserName">Indicates the account Username.</param>
''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
Public Function UserIsAdmin(ByVal UserName As String) As Boolean

    Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")

    Dim pContext As New PrincipalContext(ContextType.Machine)
    Dim pUser As New UserPrincipal(pContext)
    Dim pSearcher As New PrincipalSearcher(pUser)

    Dim User As Principal =
        (From u As Principal In pSearcher.FindAll
        Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

    If User Is Nothing Then
        Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
    End If

    Dim IsAdmin As Boolean =
        (From Group As GroupPrincipal In User.GetGroups
         Where Group.Sid = AdminGroupSID).Any

    pContext.Dispose()
    pSearcher.Dispose()
    pUser.Dispose()

    Return IsAdmin

End Function