本文整理汇总了C#中System.DirectoryServices.DirectorySearcher.FindOne方法的典型用法代码示例。如果您正苦于以下问题:C# DirectorySearcher.FindOne方法的具体用法?C# DirectorySearcher.FindOne怎么用?C# DirectorySearcher.FindOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.DirectorySearcher
的用法示例。
在下文中一共展示了DirectorySearcher.FindOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: btnLogin_Click
private void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0)
{
MessageBox.Show("用户名或者密码不能为空。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string directoryPath = "LDAP://" + GetDomainName();
string domainAndUsername = directoryPath + txtUserName.Text;
try
{
DirectoryEntry entry = new DirectoryEntry(directoryPath, txtUserName.Text, txtPassword.Text);
DirectorySearcher search = new DirectorySearcher(entry);
SearchResult result = search.FindOne();
MessageBox.Show("登录成功。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
// 如果用户名或者密码不正确,也会抛出异常。
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
示例2: GetUserImage
public BitmapImage GetUserImage(string userName)
{
using (DirectorySearcher dsSearcher = new DirectorySearcher(this.entry))
{
dsSearcher.Filter = "(&(objectClass=user) (cn=" + userName.Split('\\').Last() + "*))";
SearchResult result = dsSearcher.FindOne();
if (result == null)
return null;
using (DirectoryEntry user = new DirectoryEntry(result.Path))
{
byte[] data = user.Properties[this.imageProperty].Value as byte[];
if (data == null)
return null;
using (var stream = new MemoryStream(data))
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
}
}
}
示例3: ChangePassword
/// <summary>
/// �������û�������
/// </summary>
/// <param name="UserName">���û���</param>
/// <param name="OldPassword">������</param>
/// <param name="NewPassword">������</param>
/// <param name="DomainName">DNS����</param>
/// <returns>�ɹ������棬���ɹ����ؼ�</returns>
public static bool ChangePassword(string UserName, string OldPassword, string NewPassword, string DomainName)
{
try
{
string UserPrincipalName = UserName + "@" + DomainName;
DirectoryEntry deRootDSE = new DirectoryEntry("LDAP://RootDSE", UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
DirectoryEntry deDomain = new DirectoryEntry("LDAP://" + deRootDSE.Properties["defaultNamingContext"].Value.ToString(), UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
DirectorySearcher dsSearcher = new DirectorySearcher();
dsSearcher.SearchRoot = deDomain;
dsSearcher.SearchScope = SearchScope.Subtree;
dsSearcher.Filter = "(userPrincipalName=" + UserPrincipalName + ")";
SearchResult srResult = dsSearcher.FindOne();
if (srResult != null)
{
DirectoryEntry deUser = new DirectoryEntry(srResult.GetDirectoryEntry().Path, UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
deUser.Invoke("ChangePassword", new object[] { OldPassword, NewPassword });
deUser.CommitChanges();
return true;
}
else
return false;
}
catch //(Exception ex)
{
return false;// ex.Message;
}
}
示例4: GetDirectoryObjectById
public override DirectoryObject GetDirectoryObjectById(string id) {
if(id == null) {
throw new ArgumentNullException("id");
}
DirectoryObject directoryObject = null;
if(id.Length > 0) {
using(DirectoryEntry directoryEntry = this.GetDirectoryEntry()) {
using(DirectorySearcher directorySearcher = new DirectorySearcher(
directoryEntry,
string.Format(CultureInfo.InvariantCulture, FilterAndFormat, BaseFilter + string.Format(CultureInfo.InvariantCulture, FilterFormat, this.IdentifyingPropertyName, id)),
PropertyNames,
SearchScope.Subtree)) {
SearchResult searchResult = directorySearcher.FindOne();
if(searchResult != null) {
directoryObject = this.CreateDirectoryObjectInstance();
directoryObject.Id = GetPropertyValue(searchResult, this.IdentifyingPropertyName);
foreach(string propertyName in searchResult.Properties.PropertyNames) {
if(directoryObject.Contains(propertyName)) {
directoryObject[propertyName] = GetPropertyValue(searchResult, propertyName);
}
}
}
}
}
}
return directoryObject;
}
示例5: getGrups
static public void getGrups(string username, string group_Admin)
{
try
{
// string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", "afanasievdv");
string domain = "isea.ru";
string[] properties = new string[] { "fullname" };
// username = "afanasievdv";
DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
DirectorySearcher dirsearcher = new DirectorySearcher(adRoot);
dirsearcher.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
dirsearcher.PropertiesToLoad.Add("memberOf");
int propCount;
SearchResult dirSearchResults = dirsearcher.FindOne();
propCount = dirSearchResults.Properties["memberOf"].Count;
DirectoryEntry directoryEntry = dirSearchResults.GetDirectoryEntry();
// string dn, equalsIndex, commaIndex;
PropertyValueCollection groups = directoryEntry.Properties["memberOf"];
foreach (string g in groups)
{
string group = g.Split('=')[1].Split(',')[0];
System.Diagnostics.Debug.WriteLine(group);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
示例6: ValidarUsuarioActiveDirectory
//- Método que valida el usuario en el Active Directory
public bool ValidarUsuarioActiveDirectory(string _Path, string userId, string password)
{
DirectoryEntry deEntry = new DirectoryEntry(_Path, userId, password);
DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
bool bandera = false;
try
{
UsuarioId(userId);
dsSearcher.Filter = "(SAMAccountName=" + w_UserAD.Trim() + ")";
dsSearcher.PropertiesToLoad.Add("cn");
SearchResult result = dsSearcher.FindOne();
if (!string.IsNullOrEmpty(result.ToString()))
{
bandera = true;
}
else
{
bandera = false;
}
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception)
{
return false;
}
return bandera;
}
示例7: GetGroups
// potentially not needed due to use of the role provider
public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
示例8: Initialize
private void Initialize()
{
this.Name = Domain.Name;
var dc = Domain.FindDomainController();
string ldapPath = string.Format("LDAP://{0}/", dc.Name);
using (var adRootDSE = new DirectoryEntry(ldapPath + "RootDSE"))
{
this.DistinguishedName = adRootDSE.Properties["defaultNamingContext"][0].ToString();
this.ConfigurationNamingContext = adRootDSE.Properties["configurationNamingContext"][0].ToString();
}
using (var adDomainRoot = new DirectoryEntry(ldapPath + this.DistinguishedName))
{
this.SecurityIdentifier = new SecurityIdentifier((byte[])(adDomainRoot.Properties["objectSid"][0]), 0);
}
using (var configSearchRoot = new DirectoryEntry(ldapPath + "CN=Partitions," + this.ConfigurationNamingContext))
{
var configSearchFilter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", this.Name);
using (var configSearcher = new DirectorySearcher(configSearchRoot, configSearchFilter, new string[] { "NetBIOSName" }, System.DirectoryServices.SearchScope.OneLevel))
{
SearchResult configResult = configSearcher.FindOne();
if (configResult != null)
this.NetBiosName = configResult.Properties["NetBIOSName"][0].ToString();
else
this.NetBiosName = null;
}
}
}
示例9: GetPrimarySmtp
/// <summary>
/// Get the primary SMTP address of the given user name
/// </summary>
/// <param name="upnUserName">UPN formatted user name to look up</param>
/// <returns>Primary SMTP address of the user if found</returns>
public static string GetPrimarySmtp(string upnUserName)
{
string primarySmtp = string.Empty;
// Use the current user's identity to get their
// default SMTP address from the default domain.
// In other words - make a lot of assumptions!
// This logic is very thin but maybe it will stand up...
// Expecting the format of the identity to be
// 'DomainName\sAMAccountName', if not BOOM!
if (!upnUserName.Contains("\\"))
{
throw new ApplicationException("Unknown identity name pattern, cannot retrieve default SMTP address.");
}
// Tear off the sAMAccountName from the identity string
string sAMAccountName = upnUserName.Split(new char[] { '\\' })[1];
// Search AD for the sAMAccountName
DirectorySearcher ds = new DirectorySearcher();
ds.Filter = string.Format(System.Globalization.CultureInfo.CurrentCulture, "sAMAccountName={0}", sAMAccountName);
SearchResult result = ds.FindOne();
if (result == null)
{
// If there are no results go BOOM!
throw new ApplicationException("Directory entry not found, cannot retrieve default SMTP address.");
}
// Get the 'mail' property and assume the
// first value is the primary SMTP address
return result.Properties["mail"][0].ToString();
}
示例10: AuthenticateUser
public User AuthenticateUser(string username, string password)
{
try
{
DirectoryEntry deSystem = new DirectoryEntry();
deSystem.AuthenticationType = AuthenticationTypes.Secure;
deSystem.Username = username;
deSystem.Password = password;
// Bind to the native AdsObject to force authentication.
Object obj = deSystem.NativeObject;
DirectorySearcher ds = new DirectorySearcher(deSystem);
ds.Filter = "(SAMAccountName=" + username + ")";
ds.PropertiesToLoad.Add("name");
ds.PropertiesToLoad.Add("mail");
SearchResult sr = ds.FindOne();
if (sr == null)
{
return null;
}
DirectoryEntry de = sr.GetDirectoryEntry();
User user = new User();
user.UserId = username;
user.UserName = de.Properties["name"].Value.ToString();
user.Email = de.Properties["mail"].Value.ToString();
return user;
}
catch (Exception ex)
{
string s = ex.Message;
return null;
}
}
示例11: GetUserPicture
public Image GetUserPicture(string userName, string domain)
{
var directoryEntry = new DirectoryEntry("LDAP://" + domain);
var propertiesToLoad = new[] { "thumbnailPhoto", "samaccountname" };
var filter = $"(&(SAMAccountName={userName}))";
var directorySearcher = new DirectorySearcher(directoryEntry, filter, propertiesToLoad);
var user = directorySearcher.FindOne();
if (user == null)
{
_log.Warn($"Could not find user '{userName}' in active directory");
return null;
}
if (!user.Properties.Contains("thumbnailPhoto"))
{
var message = "LDAP did not contain a thumbnailPhoto property for " + userName;
_log.Warn(message);
return null;
}
var bytes = user.Properties["thumbnailPhoto"][0] as byte[];
if (bytes == null) return null;
using (var ms = new MemoryStream(bytes))
{
var image = Image.FromStream(ms);
return image;
}
}
示例12: AutenticarEnDominio
private static bool AutenticarEnDominio(string userDisplayName, string codigoUsuario, string password)
{
ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
DirectoryEntry entry = GetDirectoryEntry();
entry.Username = codigoUsuario;
entry.Password = password;
try
{
var ds = new DirectorySearcher(entry)
{
Filter = ("(&(objectclass=user)(objectcategory=person)(displayname=" + userDisplayName + "))")
};
ds.SearchScope = SearchScope.Subtree;
SearchResult results = ds.FindOne();
if (results != null)
{
return true;
}
entry.Close();
return false;
}
catch (Exception ex)
{
Logger.Error("Exception AutenticarEnDominio:" + ex.Message);
return false;
}
}
示例13: GetKUsr
public static KUsr GetKUsr(string userId)
{
var kUsr = new KUsr();
if (string.IsNullOrWhiteSpace(userId))
return kUsr;
kUsr.UserId = userId;//AmUtil.GetCurrentUser;
SearchResult result = null;
using (DirectoryEntry AdEntry = ConfigUtility.IsAdTLogin() ?
new DirectoryEntry(ConfigUtility.GetActiveDirectory()) :
new DirectoryEntry(ConfigUtility.GetActiveDirectory(), ConfigUtility.GetAdLoginInfo().Item1, ConfigUtility.GetAdLoginInfo().Item2))
{
using (DirectorySearcher AdSearcher = new DirectorySearcher(AdEntry))
{
AdSearcher.Filter = "(CN=" + kUsr.UserId + ")";
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name);
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name);
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name);
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name);
//AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name);
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name);
AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name);
result = AdSearcher.FindOne();
}
//AdEntry.Close();
}
if (result != null)
{
DirectoryEntry usrEntry = result.GetDirectoryEntry();
kUsr.Domain = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value.ToString();
kUsr.FName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value.ToString();
kUsr.LName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value.ToString();
kUsr.EmailId = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value.ToString();
//kUsr.UserInitials = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value == null ? null :
// usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value.ToString();
kUsr.Location = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value.ToString();
kUsr.Department = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value == null ? null :
usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value.ToString();
}
return kUsr;
}
示例14: GetSearchResult
public static SearchResult GetSearchResult(string user, string password, string LDAPPath)
{
SearchResult sRsResult = null;
DirectoryEntry entry = null;
DirectorySearcher mySearcher = null;
entry = GetDirectoryEntry(user, password, LDAPPath);
if (entry != null)
{
try
{
mySearcher = new DirectorySearcher(entry);
}
catch (COMException) { };
if (mySearcher != null)
{
try
{
string strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + user + "))";
mySearcher.Filter = strFilter;
sRsResult = mySearcher.FindOne();
}
catch (COMException) { };
}
else { };
}
else { };
return sRsResult;
}
示例15: FindUser
public static DirectoryEntry FindUser(string userName)
{
if (string.IsNullOrEmpty(LoginDomain) || !UseWindowsCreds && (string.IsNullOrEmpty(DomainName) || string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)))
{
if (EditADPrefs.Execute() != System.Windows.Forms.DialogResult.OK)
return null;
}
try
{
DirectoryEntry dom = null;
if (UseWindowsCreds)
dom = new DirectoryEntry("LDAP://" + DomainName);
else
dom = new DirectoryEntry("LDAP://" + DomainName, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
using (DirectorySearcher dsSearcher = new DirectorySearcher(dom))
{
dsSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(samaccountname={0})))", userName);
dsSearcher.PropertiesToLoad.Add("ThumbnailPhoto");
SearchResult result = dsSearcher.FindOne();
if (result == null || string.IsNullOrEmpty(result.Path))
return null;
if (UseWindowsCreds)
return new DirectoryEntry(result.Path);
return new DirectoryEntry(result.Path, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
}
}
catch (Exception e)
{
MessageBox.Show(string.Format("Failed to search for user.\r\n\r\nError was:\r\n{0}", e.Message), "A/D Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}