2013-08-14 18 views
5

gelen kullanıcı hesabı son kullanma alma Hesaplardan son kullanma tarihi almaya çalışıyorum.ActiveDirectory

Ben sadece bana hata "belirtilen atama geçerli değil" verir

DirectoryEntry user = new DirectoryEntry(iMem); 

var AccountExpiration = DateTime.FromFileTime((int)user.Properties["accountExpires"].Value); 

çalışmıyor denedim.

Ben

var AccountExpiration = user.Properties["accountExpires"]; 

Ben okuyamadı olduğum bir com nesnesi döndürür kullanın. Windows PowerShell kullanarak

, gayet iyi çalışıyor, ben bu alışkanlık iş ...

bu yüzden ben powershell kullandığımız kod

$Expires = [datetime]::FromFileTime($tmpUser.accountExpires) 

cevap

10

Sen gerçekleştirmek için System.DirectoryServices.AccountManagement ad kullanabilirsiniz alamadım bu görev. UserPrincipal'u bir PrincipalContext'dan aldığınızda, UserPrincipal.AccountExpirationDate özelliğini denetleyebilirsiniz. EğerDirectoryEntry kullanmak istiyorsunuz Eğer

PrincipalContext context = new PrincipalContext(ContextType.Domain); 

UserPrincipal p = UserPrincipal.FindByIdentity(context, "Domain\\User Name"); 

if (p.AccountExpirationDate.HasValue) 
{ 
    DateTime expiration = p.AccountExpirationDate.Value.ToLocalTime(); 
} 

Bunu yapmak:

private static long ConvertLargeIntegerToLong(object largeInteger) 
{ 
    Type type = largeInteger.GetType(); 

    int highPart = (int)type.InvokeMember("HighPart", BindingFlags.GetProperty, null, largeInteger, null); 
    int lowPart = (int)type.InvokeMember("LowPart", BindingFlags.GetProperty | BindingFlags.Public, null, largeInteger, null); 

    return (long)highPart <<32 | (uint)lowPart; 
} 

object accountExpires = DirectoryEntryHelper.GetAdObjectProperty(directoryEntry, "accountExpires"); 
var asLong = ConvertLargeIntegerToLong(accountExpires); 

if (asLong == long.MaxValue || asLong <= 0 || DateTime.MaxValue.ToFileTime() <= asLong) 
{ 
    return DateTime.MaxValue; 
} 
else 
{ 
    return DateTime.FromFileTimeUtc(asLong); 
} 
: accountExpires değerini ayrıştırma başka yolu yansıması
//assume 'user' is DirectoryEntry representing user to check 
DateTime expires = DateTime.FromFileTime(GetInt64(user, "accountExpires")); 

private Int64 GetInt64(DirectoryEntry entry, string attr) 
{ 
    //we will use the marshaling behavior of the searcher 
    DirectorySearcher ds = new DirectorySearcher(
    entry, 
    String.Format("({0}=*)", attr), 
    new string[] { attr }, 
    SearchScope.Base 
    ); 

    SearchResult sr = ds.FindOne(); 

    if (sr != null) 
    { 
     if (sr.Properties.Contains(attr)) 
     { 
      return (Int64)sr.Properties[attr][0]; 
     } 
    } 

    return -1; 
} 

kullanıyor