Привет, я хотел бы избежать печати определенных строк (действительных учетных записей) в моем цикле foreach (в GetSAM), а не печатать все.
Когда я попытаюсь сделать это, прокомментировав строку (в valSAM), которая печатает действительные учетные записи, она будет пустой в области, где была действительная учетная запись. Я понимаю, что это происходит из-за того, что foreach обрабатывает все переменные в базе данных.
Как я могу удалить промежутки между выводами?
//Get SAMAccount
private static string GetSAM(string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
string ldapFilter = "(&(objectclass=user)(objectcategory=person))";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
string readOutput;
List<string> list = new List<string>();
List<int> invalid = new List<int>();
using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
{
string samAccountName;
directorySearcher.Filter = ldapFilter;
directorySearcher.SearchScope = SearchScope.Subtree;
directorySearcher.PageSize = 1000;
using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
{
**foreach (SearchResult result in searchResultCollection)
{
samAccountName = result.Properties["sAMAccountName"][0].ToString();
if (valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword)!= true)
{
invalid.Add('1');
}
list.Add(samAccountName);
} //end of foreach**
// Count all accounts
int totalAccounts = list.Count;
// Count all invalid accounts
int invalidAccounts = invalid.Count;
Console.WriteLine("Found " + invalidAccounts + " invalid accounts out of " + totalAccounts + " user accounts.\nQuery in " + ldapAddress + " has finished.\n");
Console.WriteLine("Press [enter] to continue.\n");
readOutput = Console.ReadLine();
}//SearchResultCollection will be disposed here
}
return readOutput;
}
//Validate SAMAccount
private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
bool accountValidation = false;
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
accountValidation = ((isAccountActived != true) || (isAccountLocked));
//account is invalid
if (accountValidation)
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
} else if (isAccountActived != true)
{
builder.Append("Account is inactive.").Append('\n'); ;
}
else if (isAccountLocked)
{
builder.Append("Account is locked or has expired.").Append('\n'); ;
}
else
{
builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
}
accountValidation = false;
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
**//builder.Append("User account " + samAccountName + " is valid.").Append('\n');
accountValidation = true;
}
}
else Console.WriteLine("Nothing found.");
Console.WriteLine(builder);
}//end of using
return accountValidation;
}
Вы, вероятно, хотите писать только в том случае, если у строителя есть что-то, иначе он напечатает пустую строку. А именно, изменение
Console.WriteLine(builder);
в
if (builder.Length > 0)
{
Console.WriteLine(builder);
}
или просто
Console.Write(builder);
если вы собираетесь обрабатывать все новые строки в самом застройщике. Если вы собираетесь это сделать, используйте StringBuilder.AppendLine() вместо hardcoding '\n', как это.
valSAM
строкуConsole.WriteLine(builder)
в концеvalSAM
в нечто вроде:if (!accountValidation) { ... }
?int
totalAccounts
иinvalidAccounts
, инициализировать их0
при запуске, а затем увеличивать (variable++;
) каждый раз, когда вы добавляете элемент в список? Кроме того, вам очень повезло, что что-то вродеList<int> invalid = new List<int>(); invalid.Add('1');
даже работает ...