Skip to main content

Grab E-mail addresses

I thought to share a C#.net method that grab all the e-mail addresses from any file and It can be used for validation too.It returns an string array and I hope that you all can add some modifications on it and use it for any purpose you want.
Here is the code.

public static String[] readEmails(string file)
{
 int k = 0;
 StreamReader SR = File.OpenText(file);
 String S = SR.ReadLine();
 Dictionary myemails = new Dictionary();             
 string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
 Regex re = new Regex(pattern);        

 while (S != null)
 {             
  MatchCollection matches = re.Matches(S);

  if (matches.Count > 0)                                 
  for (int i = 0; i < matches.Count; i++)                    
  myemails.Add(i,matches[i].ToString());                

  S = SR.ReadLine();
 }
 
 string[] email = new string[myemails.Count];
 
 for (int i = 0; i < myemails.Count; i++)
  email[i]=myemails[i];

 Array.Sort(email);
 SR.Close();
 return email;
}
You have to pass the file that contains the e-mail addresses as a parameter. For eg:F:\\date2.txt If you have come up with any problem in using this do not hesitate to put a comment and I hope I'll be able to answer you.

Comments

Post a Comment