jkregala
jkregala

Reputation: 33

Truncate e-mail text string at the @ portion in C#

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 :)

Upvotes: 1

Views: 2410

Answers (3)

Dariusz Woźniak
Dariusz Woźniak

Reputation: 10350

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

Upvotes: 9

SLaks
SLaks

Reputation: 887777

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.

Upvotes: 3

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

email = email.Substring(0, email.IndexOf('@'));

Upvotes: 3

Related Questions