using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using Microsoft.Office.Interop.Excel;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace EmailListingFinal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Opens the connection to the AD
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal qbeUser = new UserPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
//Brings in the current user logged in first and last name
string currentUserF = UserPrincipal.Current.GivenName;
string currentUserL = UserPrincipal.Current.Surname;
string[] lines = System.IO.File.ReadAllLines("C:\\names.txt");
Regex rgx = new Regex("^(?![d,D]isabled)");
//Regex rgx1 = new Regex(@"^(?=[A-Za-z])(?!.*[,._()\[\]-]{2})[A-Za-z._()\[\]-]$");
int x;
//Security
for (x = 0; x < lines.Length; x++)
{
if (currentUserF + " " + currentUserL == lines[x])
{
int i = 0;
int y = 0;
//Loop that calculates how many entries are found
foreach (var found in srch.FindAll())
{
UserPrincipal foundUser = found as UserPrincipal;
if (foundUser != null && foundUser.EmailAddress != null && rgx.IsMatch(foundUser.EmailAddress))
{
string email = foundUser.EmailAddress;
string name = foundUser.DisplayName;
i++;
}
}
//Function that creates the file that the names and emails will be written to
using (StreamWriter sw = File.CreateText("C:\\emailListing.txt"))
{
//Loop that goes through all the users in the AD
foreach (var found in srch.FindAll())
{
UserPrincipal foundUser = found as UserPrincipal;
//Loop that doesnt bring in users with no name or email address
if (foundUser != null && foundUser.EmailAddress != null && rgx.IsMatch(foundUser.EmailAddress))
{
//Gets the users name and email address
string email = foundUser.EmailAddress;
string name = foundUser.DisplayName;
//Writes the data to the txt file
sw.Write(name);
sw.Write("; ");
sw.WriteLine(email);
//Function to make the progress bar load
progressBar1.Maximum = i;
progressBar1.Value = y++;
}
}
//Message that confirms the program has concluded
MessageBox.Show("Done - Please check C:\\emailListing.text to upload to excel using semicolon as the delimiter");
}
System.Windows.Forms.Application.Exit();
}
}
//Error message if the user doesn't match then exits the program
MessageBox.Show("Unathorized User");
System.Windows.Forms.Application.Exit();
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}