views:

88

answers:

3

I have a situation in ASP.NET C# wherein for example I have the email address [email protected] but I need to have the @gmail.com portion removed for all email input. Please help. Thanks :)

+2  A: 

Like this:

new MailAddress(someString).User

If the email address is invalid, this will throw an exception.

If you also need to validate the email address, you should write new MaillAddress(someString) inside of a catch block; this is the best way to validate email addresses in .Net.

SLaks
+2  A: 
email = email.Substring(0, email.IndexOf('@'));
Hasan Khan
Thanks for this comment, I've explored substring and it worked. :)
jkregala
+9  A: 

You can use MailAddress Class (System.Net.Mail):

string mailAddress = "[email protected]";
var mail = new MailAddress(mailAddress);

string userName = mail.User; // hello
string host = mail.Host; // gmail.com
string address = mail.Address; // [email protected]

In the case of wrong e-mail address (eg. lack of at sign or more than one) you have to catch FormatException, for example:

string mailAddress = "hello@gmail@";
var mail = new MailAddress(mailAddress); // error: FormatException

If you don't want to verify e-mail address, you can use Split method from string:

string mailAddress = "[email protected]";
char atSign = '@';
string user = mailAddress.Split(atSign)[0]; // hello
string host = mailAddress.Split(atSign)[1]; // gmail.com
ventr1s