本文整理汇总了C#中System.DirectoryServices.DirectoryEntry类的典型用法代码示例。如果您正苦于以下问题:C# DirectoryEntry类的具体用法?C# DirectoryEntry怎么用?C# DirectoryEntry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DirectoryEntry类属于System.DirectoryServices命名空间,在下文中一共展示了DirectoryEntry类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:cbfjay,项目名称:Aspnet.Login,代码行数:25,代码来源:Form1.cs
示例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;
}
}
}
}
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:29,代码来源:CodeNamePropertySetter.cs
示例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;
}
}
开发者ID:songques,项目名称:CSSIM_Solution,代码行数:35,代码来源:DNS.cs
示例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);
}
}
开发者ID:Warlord123,项目名称:RdpTools,代码行数:27,代码来源:RegisterLocalUser.cs
示例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;
}
开发者ID:KBurov,项目名称:WandererLib,代码行数:31,代码来源:EntityPickerDialog.cs
示例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;
}
开发者ID:julienblin,项目名称:NAntConsole,代码行数:25,代码来源:AddUserToGroupTask.cs
示例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;
}
开发者ID:imysecy,项目名称:SPLINK,代码行数:32,代码来源:ActiveDirectoryChecking.cs
示例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;
}
}
开发者ID:Tomcooper12,项目名称:NocMon,代码行数:33,代码来源:AdUsers.cs
示例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
}
}
}
开发者ID:uQr,项目名称:referencesource,代码行数:29,代码来源:DynamicVirtualDiscoSearcher.cs
示例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;
}
开发者ID:borkaborka,项目名称:gmit,代码行数:30,代码来源:AuthServices.cs
示例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;
}
开发者ID:Acceleratio,项目名称:SPDG,代码行数:25,代码来源:AD.cs
示例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; }
}
开发者ID:Vooban,项目名称:vooban.tfs.commitmonitor,代码行数:27,代码来源:TfsCheckin.cs
示例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;
}
开发者ID:djeebus,项目名称:MusicHub,代码行数:31,代码来源:ActiveDirectoryAuthenticationService.cs
示例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;
}
开发者ID:Kusado,项目名称:WindowsProjects,代码行数:7,代码来源:Program.cs
示例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();
}
开发者ID:skitsanos,项目名称:WDK9,代码行数:35,代码来源:IISManager.cs
示例16: CreateVirtual
/// <summary>
/// 创建虚拟目录
/// </summary>
public static void CreateVirtual()
{
DirectoryEntry currentSite = SiteInfo.Current.CurrentSite;//站点或虚拟目录
if (currentSite.SchemaClassName == "IIsWebServer")
currentSite = new DirectoryEntry(currentSite.Path + "/root");
DirectoryEntry vdEntry = currentSite.Children.Add(SiteInfo.Current.VirtualName, "IIsWebVirtualDir");
vdEntry.CommitChanges();
//属性设置
vdEntry.Properties["Path"][0] = SiteInfo.Current.WebPath;
vdEntry.Properties["AppFriendlyName"].Value = SiteInfo.Current.VirtualName;
vdEntry.Properties["DefaultDoc"].Value = SiteInfo.Current.DefaultDoc;
if ((int)SiteInfo.Current.IVersion >= (int)IISVersion.IIS6)
vdEntry.Properties["AppPoolId"][0] = SiteInfo.Current.AppPool;
vdEntry.Properties["AppRoot"][0] = vdEntry.Path.Replace("IIS://" + SiteInfo.Current.DomainName, "/LM");//路径特殊处理 创建应用程序
vdEntry.Invoke("AppCreate", true);
vdEntry.Properties["AccessFlags"][0] = 513;
vdEntry.Properties["AuthFlags"][0] = 1;
vdEntry.Properties["AnonymousUserName"][0] = SiteInfo.Current.UserName_iusr;
vdEntry.Properties["AnonymousUserPass"][0] = SiteInfo.Current.PassWord_iusr;
string ScriptMaps = ".aspx," + System.Environment.GetFolderPath(System.Environment.SpecialFolder.System).ToUpper().Replace("SYSTEM32", "") + @"microsoft.net\framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG";
if (!vdEntry.Properties["ScriptMaps"].Contains(ScriptMaps))
vdEntry.Properties["ScriptMaps"][0] = ScriptMaps;
if ((int)SiteInfo.Current.IVersion >= (int)IISVersion.IIS6)
CreateAppPool();
AspNetRegIIS("-s " + vdEntry.Path.Replace("IIS://" + SiteInfo.Current.DomainName + "/", ""));//路径特殊处理
vdEntry.CommitChanges();
vdEntry.RefreshCache();
currentSite.CommitChanges();
currentSite.RefreshCache();
}
开发者ID:huchao007,项目名称:bbsmax,代码行数:38,代码来源:IISManager.cs
示例17: DirectoryEntryWrapper
public DirectoryEntryWrapper(DirectoryEntry directoryEntry)
{
if(directoryEntry == null)
throw new ArgumentNullException("directoryEntry");
this._directoryEntry = directoryEntry;
}
开发者ID:HansKindberg-Net,项目名称:HansKindberg,代码行数:7,代码来源:DirectoryEntryWrapper.cs
示例18: SAMGroupsSet
internal SAMGroupsSet(UnsafeNativeMethods.IADsMembers iADsMembers, SAMStoreCtx storeCtx, DirectoryEntry ctxBase)
{
this.atBeginning = true;
this.groupsEnumerator = ((IEnumerable)iADsMembers).GetEnumerator();
this.storeCtx = storeCtx;
this.ctxBase = ctxBase;
}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:SAMGroupsSet.cs
示例19: GetProperty
public static object GetProperty(DirectoryEntry objectDE, string property)
{
if (objectDE == null)
{
throw new ArgumentNullException("objectDE", "Value cannot be null");
}
if (string.IsNullOrEmpty(property))
{
throw new ArgumentNullException("property", "Value cannot be null");
}
switch (property)
{
case "whenCreated":
case "whenChanged":
if (objectDE.Properties.Contains(property))
{
return objectDE.Properties[property].Value;
}
break;
default:
return null;
}
return null;
}
开发者ID:Eugene-Ishkov,项目名称:RestService,代码行数:28,代码来源:LdapObjectManager.cs
示例20: 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);
}
}
}
开发者ID:saiesh86,项目名称:TravelBlog,代码行数:33,代码来源:LdapUser.cs
注:本文中的System.DirectoryServices.DirectoryEntry类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论