Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse plain email address into 2 parts

Tags:

c#

How do I get the username and the domain from an email address of:

string email = "[email protected]"; //Should parse into: string username = "hello"; string domain = "example.com"; 

I'm seeking the shortest code to do this, not necessarily efficient.


Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

like image 913
Shawn Mclean Avatar asked Dec 14 '10 19:12

Shawn Mclean


1 Answers

Use the MailAddress class

MailAddress addr = new MailAddress("[email protected]"); string username = addr.User; string domain = addr.Host; 

This method has the benefit of also parsing situations like this (and others you may not be expecting):

MailAddress addr = new MailAddress("\"Mr. Hello\" <[email protected]>"); string username = addr.User; string host = addr.Host; 

In both cases above:

Debug.Assert(username.Equals("hello")); Debug.Assert(host.Equals("site.com")); 

At the top of your file with the rest of your using directives add:

using System.Net.Mail; 
like image 151
Brian R. Bondy Avatar answered Oct 16 '22 06:10

Brian R. Bondy