本文整理汇总了C#中System.DirectoryServices.DirectoryEntry类的典型用法代码示例。如果您正苦于以下问题:C# DirectoryEntry类的具体用法?C# DirectoryEntry怎么用?C# DirectoryEntry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DirectoryEntry类属于System.DirectoryServices命名空间,在下文中一共展示了DirectoryEntry类的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: SetPropertyValue
protected override void SetPropertyValue(IOguObject srcOguObject, string srcPropertyName, DirectoryEntry entry, string targetPropertyName, string context, SetterContext setterContext)
{
string srcPropertyValue = GetNormalizeddSourceValue(srcOguObject, srcPropertyName, context);
string targetPropertyValue = GetNormalizeddTargetValue(entry, targetPropertyName, context);
if (srcPropertyValue != targetPropertyValue)
{
//entry.CommitChanges();
try
{
entry.Properties[targetPropertyName].Value = srcOguObject.Properties[srcPropertyName];
// entry.CommitChanges();
}
catch (DirectoryServicesCOMException ex)
{
if (ex.ErrorCode == -2147019886)
{
//对象已存在
entry.Properties[targetPropertyName].Value = "TMP" + Environment.TickCount.ToString("X");
entry.CommitChanges();
SynchronizeContext.Current.DelayActions.Add(new DelayRenameCodeNameAction(srcOguObject, srcPropertyName, entry.NativeGuid, targetPropertyName));
}
else
{
throw;
}
}
}
}
示例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: CreateLocalUser
//http://support.microsoft.com/kb/306273
//http://www.gotdotnet.ru/blogs/sergeyhomyuk/10326/
public static String CreateLocalUser(string login, string fullName, string password, TServer Server)
{
try
{
DirectoryEntry root = new DirectoryEntry(string.Format("WinNT://{0},computer", Server.IP));
using (DirectoryEntry user = root.Children.Add(login, "user"))
{
user.Properties["FullName"].Value = fullName;
user.Properties["Description"].Value = DateTime.Now.ToString();
user.Invoke("SetPassword", new object[] { password });
user.CommitChanges();
string UserPath = user.Path.ToString().Replace(Server.IP, Server.Name);
DirectoryEntry grp = root.Children.Find("Спутник ОТЦ3 Челябинск", "group");
if (grp != null) { grp.Invoke("Add", new object[] { UserPath }); }
return String.Format("Пользователь {0} создан на сервере {1}.", login, Server);
}
}
catch (COMException e)
{
return String.Format("Пользователь {0} не создан на сервере {1}. Ошибка: '{2}'", login, Server,e.Message);
}
}
示例5: GetDomainName
private static string GetDomainName(string dnsName)
{
string defaultNamingContext;
string rootDomainNamingContext;
using (var rootDSE = new DirectoryEntry("LDAP://RootDSE")) {
defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();
rootDomainNamingContext = rootDSE.Properties["rootDomainNamingContext"].Value.ToString();
}
using (
var domainRoot = defaultNamingContext.Equals(rootDomainNamingContext, StringComparison.InvariantCultureIgnoreCase)
? new DirectoryEntry($"LDAP://CN=Partitions,CN=Configuration,{defaultNamingContext}")
: new DirectoryEntry($"LDAP://CN=Partitions,CN=Configuration,{rootDomainNamingContext}")) {
try {
foreach (DirectoryEntry c in domainRoot.Children) {
try {
if (c.Properties["dnsRoot"].Value.ToString().Equals(dnsName, StringComparison.InvariantCultureIgnoreCase)) {
return c.Properties["NetBIOSName"].Value.ToString();
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch {}
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch {}
}
return string.Empty;
}
示例6: AddUserToLocalGroup
protected bool AddUserToLocalGroup(string user, string groupName, string domainName, string machine)
{
bool reponse = false;
try
{
string userPath = string.Format("WinNT://{0}/{1},user", domainName, user);
string groupPath = string.Format("WinNT://{0}/{1},group", machine, groupName);
using (DirectoryEntry groupe = new DirectoryEntry(groupPath))
{
groupe.Invoke("Add", userPath);
groupe.CommitChanges();
groupe.Close();
}
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
Log(Level.Error, E.Message.ToString());
}
return reponse;
}
示例7: GetDomains
public ArrayList GetDomains()
{
ArrayList arrDomains = new ArrayList();
DirectoryEntry ParentEntry = new DirectoryEntry();
try
{
ParentEntry.Path = "WinNT:";
foreach (DirectoryEntry childEntry in ParentEntry.Children)
{
switch (childEntry.SchemaClassName)
{
case "Domain":
{
arrDomains.Add(childEntry.Name);
break;
}
default:
{
break;
}
}
}
}
catch (Exception e)
{
}
finally
{
ParentEntry = null;
}
return arrDomains;
}
示例8: GetADUsers
public List<User> GetADUsers()
{
try
{
List<User> AdUsers = new List<User>();
string domainPath = "LDAP://OU=Users,OU=Cobweb Solutions Ltd,DC=cobwebsolutions,DC=com";
DirectoryEntry searchroot = new DirectoryEntry(domainPath);
DirectorySearcher search = new DirectorySearcher(searchroot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("displayname");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int i = 0; i < resultCol.Count; i++)
{
result = resultCol[i];
User adUser = new User();
adUser.DisplayName = (string)result.Properties["displayname"][0];
adUser.UserName = (string)result.Properties["samaccountname"][0];
AdUsers.Add(adUser);
}
}
return AdUsers;
}
catch (Exception ex)
{
return null;
}
}
示例9: SearchSubDirectories
// -------------------------------------------------------------------------------
// Look in virtual subdirectories.
protected override void SearchSubDirectories(string nameAdsiDir) {
if ( CompModSwitches.DynamicDiscoverySearcher.TraceVerbose ) Debug.WriteLine( "DynamicVirtualDiscoSearcher.SearchSubDirectories(): nameAdsiDir=" + nameAdsiDir);
DirectoryEntry vdir = (DirectoryEntry)Adsi[nameAdsiDir]; //may be already bound
if (vdir == null) {
if ( !DirectoryEntry.Exists(nameAdsiDir) )
return;
vdir = new DirectoryEntry(nameAdsiDir);
Adsi[nameAdsiDir] = vdir;
}
foreach (DirectoryEntry obj in vdir.Children) {
DirectoryEntry child = (DirectoryEntry)Adsi[obj.Path];
if (child == null) {
child = obj;
Adsi[obj.Path] = obj;
} else {
obj.Dispose();
}
AppSettings settings = GetAppSettings(child);
if (settings != null) {
ScanDirectory(child.Path); //go down ADSI path
}
}
}
示例10: GetClientRoles
internal static IEnumerable<BplRole> GetClientRoles(string loginName) {
try {
using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) {
try {
var groups = user.GetAuthorizationGroups();
var roles = groups.Select(g => BplRole.Get(g.Name)).Where(r => r != null).ToArray();
return roles;
} catch (PrincipalOperationException pex) {
Log.Exception(pex, Severity.Warning, "Unable to retrive client roles on trusted domain. Fall back to untrusted.");
}
//TK: Fallback to untrusted communication or DNS issues. I do not believe i need to do this!
var usr = (DirectoryEntry)user.GetUnderlyingObject();
var dgroups = usr.Invoke("Groups");
var droles = new List<BplRole>();
foreach (var g in (IEnumerable)dgroups) {
var ge = new DirectoryEntry(g);
var role = BplRole.Get(ge.Name.RemoveAll("CN="));
if (role != null) {
droles.Add(role);
}
}
return droles;
}
}
} catch (Exception e) {
Log.Exception(e, "Unable to retrive client roles");
}
return null;
}
示例11: 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;
}
示例12: GetFullName
private static string GetFullName(string username)
{
try
{
if (_usernameMappings.ContainsKey(username))
return _usernameMappings[username];
var de = new DirectoryEntry("WinNT://" + username.Replace("\\", "/"));
var fullname = de.Properties["fullName"].Value.ToString();
var parts = fullname.Split(',');
if (parts.Length >= 2)
{
var correctedName = string.Format("{0} {1}", parts[1].Trim(), parts[0].Trim());
fullname = correctedName;
}
_usernameMappings.Add(username, fullname);
var formatter = new BinaryFormatter();
using(var fs = new FileStream(USER_MAPPING_FILENAME, FileMode.OpenOrCreate))
formatter.Serialize(fs, _usernameMappings);
return fullname;
}
catch { return username; }
}
示例13: GetFullNameFromActiveDirectory
private static string GetFullNameFromActiveDirectory(string username)
{
// got from http://milanl.blogspot.com/2008/08/retrieve-full-name-from-active.html
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = username.IndexOf('\\');
if (idx == -1)
{
idx = username.IndexOf('@');
}
if (idx != -1)
{
strDomain = username.Substring(0, idx);
strName = username.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = username;
}
DirectoryEntry obDirEntry = null;
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
string name = (string)coll["FullName"].Value;
return string.IsNullOrWhiteSpace(name) ? username : strName;
}
示例14: GetUsers
private static SearchResultCollection GetUsers(DirectoryEntry ad, string ldapFilter)
{
var search = new DirectorySearcher(ad, ldapFilter);
search.SearchScope = AppSettings.GeneralSettings.SearchScope;
var results = search.FindAll();
return results;
}
示例15: CreateFtpServerVirtualDirectory
public void CreateFtpServerVirtualDirectory(int iFtpSiteID, string sVirtualDirectoryName, string sPath,
bool bCanRead, bool bCanWrite, bool isRoot)
{
DirectoryEntry directoryEntry1;
DirectoryEntry directoryEntry2;
if (!isRoot)
{
directoryEntry1 = new DirectoryEntry(String.Concat("IIS://localhost/MSFTPSVC/", iFtpSiteID, "/ROOT"));
var locals = new object[] {"IISFtpVirtualDir", sVirtualDirectoryName};
directoryEntry2 = (DirectoryEntry) directoryEntry1.Invoke("Create", locals);
}
else
{
directoryEntry1 = new DirectoryEntry(String.Concat("IIS://localhost/MSFTPSVC/", iFtpSiteID));
var locals = new object[] {"IISFtpVirtualDir", "ROOT"};
directoryEntry2 = (DirectoryEntry) directoryEntry1.Invoke("Create", locals);
}
directoryEntry2.Properties["Path"][0] = sPath;
int i = 0;
if (bCanRead)
{
i++;
}
if (bCanWrite)
{
i += 2;
}
directoryEntry2.Properties["AccessFlags"][0] = i;
directoryEntry2.CommitChanges();
directoryEntry1.Invoke("SetInfo", new object[0]);
directoryEntry1.CommitChanges();
directoryEntry1.Dispose();
}