String 检查“是否存在”@&引用;及"&引用;串串的?

String 检查“是否存在”@&引用;及"&引用;串串的?,string,email,character,String,Email,Character,我正在建立一个基本的联系人管理器,我想知道如何检查电子邮件地址是否有“@”和“.”字符,以便进行验证。我已经做了一些环顾四周,我不太确定,我是否能够以某种方式使用“IndexOf”?任何帮助都将不胜感激,这就是我的代码到目前为止的样子 public static string GetValidEmail(string message, List<Contact> contactList) { // declare variables string validStrin

我正在建立一个基本的联系人管理器,我想知道如何检查电子邮件地址是否有“@”和“.”字符,以便进行验证。我已经做了一些环顾四周,我不太确定,我是否能够以某种方式使用“IndexOf”?任何帮助都将不胜感激,这就是我的代码到目前为止的样子

public static string GetValidEmail(string message, List<Contact> contactList)
{
    // declare variables
    string validString;
    bool duplicateEmail;

    do
    {

        duplicateEmail = false;
        //ask user for input, remove empty space from beginning/end if it exists
        Console.Write(message);
        validString = Console.ReadLine().Trim();


        //check for empty string
        while (string.IsNullOrEmpty(validString))
        {
            //display error message, ask for user input 
            Console.WriteLine("ERROR: You cannot enter an empty value, please try again");
            Console.Write(message);
            validString = Console.ReadLine();
        }
        //check for duplicate email, if duplicate is found, restart do until loop
        for (int index = 0; index < contactList.Count && duplicateEmail == false; index++)
        {
            if (contactList[index].EmailAddress.ToUpper().Equals(validString.ToUpper()))
            {
                Console.WriteLine("ERROR: You cannot enter duplicate email addresses, please try again");
                duplicateEmail = true;
            }
        }
    } while (duplicateEmail);

    return validString;
}
public静态字符串GetValidEmail(字符串消息、列表联系人列表)
{
//声明变量
字符串有效字符串;
bool-duplicate电子邮件;
做
{
重复电子邮件=假;
//请求用户输入,如果存在,则从开头/结尾删除空白
控制台。写入(消息);
validString=Console.ReadLine().Trim();
//检查是否有空字符串
while(string.IsNullOrEmpty(validString))
{
//显示错误消息,请求用户输入
WriteLine(“错误:不能输入空值,请重试”);
控制台。写入(消息);
validString=Console.ReadLine();
}
//检查重复的电子邮件,如果发现重复,重新启动do直到循环
对于(int index=0;index
不确定这是否正是您所需要的,但我通常在需要验证电子邮件地址时使用类似的方法

    public bool IsValidEmail(string mail)
    {
        try
        {
            new MailAddress(mail);
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

我不推荐异常捕获方法。在大多数情况下,正则表达式匹配会做得很好

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z");    
看 详情请参阅