本文整理汇总了C#中System.DirectoryServices.DirectorySearcher类的典型用法代码示例。如果您正苦于以下问题:C# DirectorySearcher类的具体用法?C# DirectorySearcher怎么用?C# DirectorySearcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DirectorySearcher类属于System.DirectoryServices命名空间,在下文中一共展示了DirectorySearcher类的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: GetStudentClass
private async Task<string> GetStudentClass(string studentnumber)
{
await Task.Delay(0);
try
{
using (DirectoryEntry dir = new DirectoryEntry(LDAP_URL)) //Instantiate dir entry and pass the domain
{
dir.Username = USERNAME;
dir.Password = PASSWORD;
using (DirectorySearcher search = new DirectorySearcher(dir)) //Search query instance
{
search.Filter = "(&(objectClass=user)(pager=" + studentnumber + "))"; //Filter by pager (Student number)
search.PropertiesToLoad.Add("telephoneNumber"); //Allows us to use the "pager" property to search by student ID
SearchResult searchresult = search.FindOne();
using (DirectoryEntry uEntry = searchresult.GetDirectoryEntry())
{
string leerlingnaam = uEntry.Properties["givenName"].Value.ToString() + " " + uEntry.Properties["sn"].Value.ToString(); //Store full student name in string
string LDAPDescription = uEntry.Properties["memberOf"][1].ToString();
//Clean it up to only return the students class id
return LDAPDescription.Substring(LDAPDescription.IndexOf('=') + 1, LDAPDescription.IndexOf(',') - 3) + "@" + leerlingnaam;
}
}
}
}
catch
{
return "";
}
}
示例3: 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;
}
示例4: LdapUser
public LdapUser(DirectoryEntry adentry, String userName, LdapSettings ldapSettings)
{
userid = new LdapAttribute("userid", userName);
DirectorySearcher ds = new DirectorySearcher(adentry);
ds.Filter = "(&(sAMAccountName=" + userName + "))";
SearchResult result = ds.FindOne();
DirectoryEntry ent = null;
if (result != null)
{
ent = result.GetDirectoryEntry();
}
if (ent != null)
{
if (ent.Properties["cn"].Value != null)
{
commonname = new LdapAttribute("commonname", ent.Properties["cn"].Value.ToString());
}
else
{
commonname = new LdapAttribute("commonname", userName);
}
if (ent.Properties["mail"].Value != null)
{
email = new LdapAttribute("email", ent.Properties["mail"].Value.ToString());
}
else
{
email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
}
}
}
示例5: GetStatus
public bool GetStatus()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("userAccountControl");
try
{
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
string statusNames = result.Properties["userAccountControl"][0].ToString();
if ("512".Equals(statusNames))
{
return true;
}
// 512 可用账户
// 514 账户无效
// 528 账户锁定
// 8389120 密码过期
return false;
}
catch (Exception ex)
{
return false;
//throw new Exception("Error obtaining userAccountControl names. " + ex.Message);
}
}
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
// TODO this todo was here for ages
var dc = new DirectoryContext(DirectoryContextType.Domain, "ptsecurity.ru");
var address = Request.Params["address"];
var filter = "Address=" + address;
var result = "";
var domain = Domain.GetDomain(dc);
// this is our vulnerabilitiy of LDAP injection *in this file*
// FIXED: AI issue #3, High, LDAP Injection, https://github.com/SDLTestAccount/IT/issues/3
// GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx?address=%7bfilter%7d+%3d+* HTTP/1.1
// Host:localhost
var ds = new DirectorySearcher(domain.GetDirectoryEntry());//, filter);
using (var src = ds.FindAll())
{
// TODO it was edit here by developer 1 year ago
foreach (var res in src)
{
result = res.ToString();
}
}
// let's go
// this is our first vulnerability of XSS in this file
// we will demonstrate False Positive scenario here (FP Marker)
// FP: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4
// GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1
// Host:localhost
// (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>"))
Response.Write(result);
// this is our second vulnerability of XSS in this file
// we will demonstrate what happen if developer fails with his fix (VERIFY Marker)
// FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4
// GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1
// Host:localhost
// (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>"))
Response.Write("result");
// this is our third vulnerability of XSS in this file
// we will demonstrate what happen if we really fix vulnerability (VERIFY Marker)
// FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4
// GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1
// Host:localhost
// (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>"))
Response.Write("result");
// this is our fourth vulnerability of XSS in this file
// we will demonstrate what happen if developer want to cheat (FIXED Marker)
// FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4
// GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1
// Host:localhost
// (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>"))
Response.Write("result");
}
示例7: GetDomainList2
public static List<string> GetDomainList2()
{
List<string> domainList = new List<string>();
string sRootDomain;
System.DirectoryServices.DirectoryEntry deRootDSE;
System.DirectoryServices.DirectoryEntry deSearchRoot;
System.DirectoryServices.DirectorySearcher dsFindDomains;
System.DirectoryServices.SearchResultCollection srcResults;
deRootDSE = new System.DirectoryServices.DirectoryEntry("GC://RootDSE");
sRootDomain = "GC://" + deRootDSE.Properties["rootDomainNamingContext"].Value.ToString();
deSearchRoot = new System.DirectoryServices.DirectoryEntry(sRootDomain);
dsFindDomains = new System.DirectoryServices.DirectorySearcher(deSearchRoot);
dsFindDomains.Filter = "(objectCategory=domainDNS)";
dsFindDomains.SearchScope = System.DirectoryServices.SearchScope.Subtree;
srcResults = dsFindDomains.FindAll();
foreach (System.DirectoryServices.SearchResult srDomain in srcResults)
{
domainList.Add(srDomain.Properties["name"][0].ToString());
}
return domainList;
}
示例8: RequesterEmail_comboBox_SelectedIndexChanged
private void RequesterEmail_comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Get user first name and last name by email
string mail = RequesterEmail_comboBox.Text;
DirectoryEntry entry = new DirectoryEntry();
DirectorySearcher adsearcher = new DirectorySearcher(entry);
adsearcher.Filter = "(&(objectClass=user)(mail=" + mail + "))";
adsearcher.PropertiesToLoad.Add("givenName");
adsearcher.PropertiesToLoad.Add("sn");
adsearcher.PropertiesToLoad.Add("mail");
SearchResult result = adsearcher.FindOne();
if (result == null)
MessageBox.Show("Email Does Not Exist !!" + Environment.NewLine + "Please Check Your Spelling !!");
if (result != null)
{
DirectoryEntry employee = result.GetDirectoryEntry();
string FirstName = employee.Properties["givenName"].Value.ToString();
string LastName = employee.Properties["sn"].Value.ToString();
RequesterFirstName_txtBox.Text = FirstName;
RequesterLastName_txtBox.Text = LastName;
}
}
示例9: AuthenticateUser
private static bool AuthenticateUser(string credentials)
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
var credentialsArray = credentials.Split(':');
var username = credentialsArray[0];
var password = credentialsArray[1];
if (string.IsNullOrEmpty(username))
{
return false;
}
var directoryEntry = new DirectoryEntry(Ldap, username, password);
var searchAdForUser = new DirectorySearcher(directoryEntry) { Filter = "(&(objectClass=user)(anr=" + username + "))" };
var retrievedUser = searchAdForUser.FindOne();
if (retrievedUser == null)
{
return false;
}
var identity = new GenericIdentity(username);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
示例10: GetRolesForUser
public override string[] GetRolesForUser(string username)
{
var allRoles = new List<string>();
var root = new DirectoryEntry(ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
ConnectionUsername, ConnectionPassword);
var searcher = new DirectorySearcher(root, String.Format(CultureInfo.InvariantCulture,
"(&(objectClass=user)({0}={1}))", AttributeMapUsername, username));
searcher.PropertiesToLoad.Add("memberOf");
SearchResult result = searcher.FindOne();
if (result != null && !string.IsNullOrEmpty(result.Path))
{
DirectoryEntry user = result.GetDirectoryEntry();
PropertyValueCollection groups = user.Properties["memberOf"];
foreach (string path in groups)
{
string[] parts = path.Split(',');
if (parts.Length > 0)
{
foreach (string part in parts)
{
string[] p = part.Split('=');
if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
{
allRoles.Add(p[1]);
}
}
}
}
}
return allRoles.ToArray();
}
示例11: GetComputers
public static List<string> GetComputers()
{
List<string> ComputerNames = new List<string>();
DirectoryEntry entry = new DirectoryEntry("LDAP://transnetwork.local/OU=Phoenix-DC,DC=transnetwork,DC=local");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)"); //se buscan solamente objetos de ltipo computadora / server
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult resEnt in mySearcher.FindAll())
{
//"CN=SGSVG007DC"
string ComputerName = resEnt.GetDirectoryEntry().Name;
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0, "CN=".Length);
ComputerNames.Add(ComputerName);
}
mySearcher.Dispose();
entry.Dispose();
// Console.ReadLine();
return ComputerNames;
}
示例12: FindAccountByEmail
public static string FindAccountByEmail(string pEmailAddress)
{
string filter = string.Format("(proxyaddresses=SMTP:{0})", pEmailAddress);
using (DirectoryEntry gc = new DirectoryEntry("GC:"))
{
foreach (DirectoryEntry z in gc.Children)
{
using (DirectoryEntry root = z)
{
using (DirectorySearcher searcher = new DirectorySearcher(root, filter, new string[] { "mailNickname" }))
{
searcher.ReferralChasing = ReferralChasingOption.All;
SearchResultCollection result = searcher.FindAll();
foreach (SearchResult item in result)
{
foreach (object value in item.Properties["mailNickName"])
{
return value.ToString();
}
}
}
}
}
}
return null;
}
示例13: GetNetBIOSDomains
private List<ADDomain> GetNetBIOSDomains()
{
List<ADDomain> ret = new List<ADDomain>();
DirectoryEntry RootDSE = new DirectoryEntry("LDAP://rootDSE");
// Retrieve the Configuration Naming Context from RootDSE
string configNC = RootDSE.Properties["configurationNamingContext"].Value.ToString();
// Connect to the Configuration Naming Context
DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC);
// Search for all partitions where the NetBIOSName is set.
DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot);
configSearch.Filter = ("(NETBIOSName=*)");
// Configure search to return dnsroot and ncname attributes
configSearch.PropertiesToLoad.Add("dnsroot");
configSearch.PropertiesToLoad.Add("NETBIOSName");
SearchResultCollection forestPartitionList = configSearch.FindAll();
// Loop through each returned domain in the result collection
foreach (SearchResult domainPartition in forestPartitionList)
{
ADDomain ad = new ADDomain();
ad.Name = domainPartition.Properties["NETBIOSName"][0].ToString();
ad.Path = domainPartition.Properties["NETBIOSName"][0].ToString();
ret.Add(ad);
}
return ret;
}
示例14: Authenticate
public bool Authenticate(string userName, string pwd)
{
//Get an entry to Active Directory
using (DirectoryEntry dirEntry = CreateDirectoryEntry(userName, pwd))
{
//Instansiate a new Active Directory searcher, set filter and properties
using (DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry))
{
//Set search filter
dirSearcher.Filter = "(sAMAccountName=" + userName + ")";
SearchResult searchResult;
try
{
searchResult = dirSearcher.FindOne();
}
catch (Exception err)
{
//The domain is not available or the client do not have permission to do the search.
//Check userName and/or passWord.
return false;
}
if (searchResult != null)
{
//User exist in Active Directory.
return true;
}
//User does not exist in Active Directory.
return false;
}
}
}
示例15: FindUserByLogin
public static UserEntity FindUserByLogin(string login)
{
// Parse the string to check if domain name is present.
int idx = login.IndexOf('\\');
if (idx == -1)
{
idx = login.IndexOf('@');
}
string strName = idx != -1 ? login.Substring(idx + 1) : login;
const string connection = "LDAP://softserveinc.com";
var dssearch = new DirectorySearcher(connection) { Filter = "(sAMAccountName=" + strName + ")" };
var sresult = dssearch.FindOne();
DirectoryEntry dsresult = sresult.GetDirectoryEntry();
var result = new UserEntity
{
Login = "SOFTSERVE\\" + login,
Name = dsresult.Properties["displayName"][0].ToString(),
Mail = dsresult.Properties["mail"][0].ToString(),
Department = dsresult.Properties["department"][0].ToString(),
Office = dsresult.Properties["physicalDeliveryOfficeName"][0].ToString()
};
return result;
}