本次练习的目的是使用LinQ to XML,正则表达式,明天在这个基础上练习使用序列化和反序列化,继续加点儿小功能。
首先,这是一个窗体程序,设计如下:
存放用户名和密码的XML如下:
实现的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq; namespace CheckInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "请输入用户名,格式:qarootdc\\jqhuang")
{
textBox1.Text = "";
} } private void textBox2_TextChanged_1(object sender, EventArgs e)
{
if (textBox2.Text == "请输入密码")
{
textBox2.Text = "";
}
} private void button1_Click(object sender, EventArgs e)
{
if (isValidUserName(textBox1.Text) == false)
{
MessageBox.Show("用户名格式不正确!请重新输入!");
textBox1.Text = "";
}
else
{
//用户名格式正确.
CheckUserAndPwd(textBox1.Text,textBox2.Text);
}
} private void CheckUserAndPwd(string username, string pwd)
{
//读取UserInfo.xml检测user是否存在
XDocument userInfo = XDocument.Load(@"C:\Users\jqhuang\Desktop\UserInfo.xml");
var result = from userElement in userInfo.Element("System").Element("users").Elements() where userElement.Element("username").Value.ToString() == textBox1.Text.ToString() select userElement.Element("pwd").Value;
if (result != null)
{
foreach (var password in result)
{
if (password == pwd)
{
MessageBox.Show("用户名和密码匹配成功!");
}
else
{
MessageBox.Show("用户名和密码不匹配,请重新输入密码");
textBox2.Text = "";
}
}
}
else
{
MessageBox.Show("您输入的用户不存在!");
}
} bool isValidUserName(string userName)
{
return Regex.IsMatch(userName,@"^.+\\.+$");
}
}
}
运行效果图如下——
1、用户名不存在的情况:
/
2、用户名和密码不匹配的情况:
3、用户名格式不正确的情况(用正则表达式验证):
4、用户名和密码匹配成功的情况: