首页 > 编程 > C# > 正文

C#加XML文件非流读写方法

2023-05-15 12:29:36
字体:
来源:转载
供稿:网友

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml; //重要
using System.IO;
// 本程序将演练XML文挡的读与写
// 也就是XMLReader和XMLWriter
namespace test11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            FlueList();
        }
        // 刷新显示ListBox显示的内容
        private void FlueList()
        {
            try
            {
                listBox1.Items.Clear();
                FileStream fs = new FileStream("myTestXML.xml", FileMode.Open);
                XmlReader tr = XmlReader.Create(fs);
                while (!tr.EOF)
                {
                    if (tr.MoveToContent() == XmlNodeType.Element && tr.Name == "Username")
                    {
                        listBox1.Items.Add(tr.ReadElementString());
                    }
                    tr.Read();
                }
                fs.Close();
                tr.Close();
            }
            catch
            {
                // 导入时遇到无法导入数据,则文件出错,将提示用户删除文件并建立新文件信息。
                MessageBox.Show("文挡不可用,无法导入!", "错误");
                if (MessageBox.Show("是否建立新的用户文挡?/n此操作将删除以前所有用户数据", "程序提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    // 建立新文件,此用一个无参数函数重载。
                    CreateNewFile();
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string username = textBox1.Text;
            string password = textBox2.Text;
            // 需要检查用户名和密码同时不能为空,并且不能和记录相重复。
            if (username != "" && password != "" && checkReport(username, password))
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load("myTestXML.xml");
                    XmlElement User = doc.CreateElement("User");
                    User.SetAttribute("UserSettig", "Customer");
                    // 创建一个Username标签
                    XmlElement newUsername = doc.CreateElement("Username");
                    newUsername.InnerText = username;
                    User.AppendChild(newUsername);
                    // 创建一个Password标签
                    XmlElement newPassword = doc.CreateElement("Password");
                    newPassword.InnerText = password;
                    User.AppendChild(newPassword);
                    doc.DocumentElement.AppendChild(User);
                    // 将以上信息写入到xml文件。
                    XmlTextWriter tr = new XmlTextWriter("myTestXML.xml", null);
                    tr.Formatting = Formatting.Indented;
                    doc.WriteContentTo(tr);
                    tr.Close();
                    MessageBox.Show("写入成功!", "成功");
                    FlueList();
                    // 以上条件通过后,方可进行写入操作。
                    // 此方法是将XML文挡重写,记录全无,因此舍弃此方法。
                    // 此方法在后面用于错误处理,建立新文件时。
                    /*
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    settings.NewLineOnAttributes = true;
                    XmlWriter thisWriter = XmlWriter.Create("myTestXML.xml", settings);
                    // 首行的声明
                    thisWriter.WriteStartDocument();
                    // 开始输入内容到文件中
                    thisWriter.WriteStartElement("User");
                    thisWriter.WriteAttributeString("UserSetting", "Customer");
                    thisWriter.WriteElementString("Username", username);
                    thisWriter.WriteElementString("Password", password);
                    thisWriter.WriteEndElement();
                    thisWriter.WriteEndDocument();
                    thisWriter.Flush();
                    thisWriter.Close();
                    MessageBox.Show("写入成功!", "成功");
                    */
                }
                catch
                {
                    CreateNewFile(username, password);
                }
            }
            else
            {
                MessageBox.Show("请确定输入是否正确或有重名和密码重复", "请检查");
            }
        }
        // 如果文件读写出错,则删除建立一个新文件。
        // 此函数有一个无参数的函数重载。
        // 好象这个有参数的函数也没什么用处。唉……不知道当初怎么想的。
        private void CreateNewFile(string username, string password)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            XmlWriter thisWriter = XmlWriter.Create("myTestXML.xml", settings);
            // 首行的声明
            thisWriter.WriteStartDocument();
            // 开始输入内容到文件中
            thisWriter.WriteStartElement("UserList");
            thisWriter.WriteStartElement("User");
            thisWriter.WriteAttributeString("UserSetting", "Customer");
            thisWriter.WriteElementString("Username", username);
            thisWriter.WriteElementString("Password", password);
            thisWriter.WriteEndElement();
            thisWriter.WriteEndElement();
            thisWriter.WriteEndDocument();
            thisWriter.Flush();
            thisWriter.Close();
            MessageBox.Show("写入成功!", "成功");
        }
        // 上面创建新文件的函数的无参数重载部分。
        private void CreateNewFile()
        {
            try
            {
                // 如果文件存在则删除该文件,建立正确的新文件。
                if (File.Exists("myTestXML.xml"))
                {
                    File.Delete("myTestXML.xml");
                }
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = true;
                XmlWriter thisWriter = XmlWriter.Create("myTestXML.xml", settings);
                // 首行的声明
                thisWriter.WriteStartDocument();
                // 开始输入内容到文件中
                thisWriter.WriteStartElement("UserList");
                thisWriter.WriteEndElement();
                thisWriter.WriteEndDocument();
                thisWriter.Flush();
                thisWriter.Close();
            }
            catch
            {
                MessageBox.Show("建立新文挡失败!/n请检查文件 myTestXML.xml 是否只读!", "程序错误");
            }
        }
        // 检查是否有重复的用户名和密码,此函数返回一个Bool值
        private bool checkReport(string username, string password)
        {
            try
            {
                FileStream fs = new FileStream("myTestXML.xml", FileMode.Open);
                XmlReader tr = XmlReader.Create(fs);
                string thisusername = "", thispassword = "";
                while (!tr.EOF)
                {
                    if (tr.MoveToContent() == XmlNodeType.Element && tr.Name == "Username")
                    {
                        thisusername = tr.ReadElementString();
                    }
                    else if (tr.MoveToContent() == XmlNodeType.Element && tr.Name == "Password")
                    {
                        thispassword = tr.ReadElementString();
                    }
                    if (thisusername == username && thispassword == password)
                    {
                        tr.Close();
                        fs.Close();
                        return false;
                    }
                    tr.Read();
                }
                fs.Close();
                tr.Close();
                return true;
            }
            catch
            {
                // 错误处理,如果文挡不存在,或者文挡错误,将删除文挡,并从新建立。
                MessageBox.Show("文挡不可用,无法查询!", "错误");
                if (MessageBox.Show("是否建立新的用户文挡?/n此操作将删除以前所有用户数据", "程序提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    // 调用无参数函数重载版本建立新文件。
                    CreateNewFile();
                }
                return true;
            }
        }
        // 检查用户名和密码是否可用的函数。
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "" && textBox2.Text != "" && checkReport(textBox1.Text, textBox2.Text))
            {
                MessageBox.Show("此用户名和密码可以用", "通过");
            }
            else
            {
                MessageBox.Show("此用户名和密码不可用", "未通过");
            }
        }
        // 退出该程序。
        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表