当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

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

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:47:19

:2010-08-18 09:06:00

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
            {
                // 错误处理,如果文挡不存在,

[1] [2]  下一页


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