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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With