将数据保存并加载到xml

时间:2016-12-04 18:07:36

标签: c# xml

所以我正在使用注册表格制作登录申请,但我需要一些帮助。我想保存xml中的所有帐户信息,我有点可以做,我创建了一个表单,我可以保存并加载1个用户到xml使用savefiledialog,这是代码:

xml类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;

namespace Login_Form
{
    public class xmlSave
    {
        public static void SaveData(object IClass, string filename)
        {
            StreamWriter writer = null;
            try
            {
                XmlSerializer xml = new XmlSerializer((IClass.GetType()));
                writer = new StreamWriter(filename);
                xml.Serialize(writer, IClass);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
                writer = null;
            }
        }
    }

    public class xmlLoad<T>
    {
        public static Type type;

        public xmlLoad()
        {
            type = typeof(T);
        }

        public T LoadData(string filename)
        {
            T result;
            XmlSerializer xml = new XmlSerializer(type);
            FileStream fs = new FileStream(filename, FileMode.Open,     FileAccess.Read, FileShare.Read);
            result = (T)xml.Deserialize(fs);
            fs.Close();
            return result;
        }
    }
}

这是保存和加载代码:

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.IO;
using System.Xml.Serialization;

namespace Login_Form    
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            saveFileDialog.InitialDirectory =     @"C:\Users\Felix\Documents\visual studio 2013\Projects\Login Form\Login     Form\bin\Debug";
            saveFileDialog.Filter = "xml Files (*.xml)|*.xml";
            saveFileDialog.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;

            if(saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                User user = new User();
                user.FName = textBox1.Text;
                user.LName = textBox2.Text;
                user.Username = textBox3.Text;
                user.Email = textBox4.Text;
                user.Password = textBox5.Text;
                xmlSave.SaveData(user, saveFileDialog.FileName);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            User user = new User();
            xmlLoad<User> loadUser = new xmlLoad<User>();

            user = loadUser.LoadData("test.xml");
            textBox1.Text = user.FName;
            textBox2.Text = user.LName;
            textBox3.Text = user.Username;
            textBox4.Text = user.Email;
            textBox5.Text = user.Password;    
        }
    }

    public class User
    {
        private string fName;
        private string lName;
        private string username;
        private string email;
        private string password;

        public string FName
        {
            get { return fName; }
            set { fName = value; }
        }

        public string LName
        {
            get { return lName; }
            set { lName = value; }
        }

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        public string Email
        {
            get { return email; }
            set { email = value; }
        }

       public string Password
        {
            get { return password; }
            set { password = value; }
        }
    }
}

这允许我将信息从5个文本框保存到xml文件但只有1个用户,我想知道如何保存多个用户以及如何将其用作登录系统(没有服务器,现在只有本地) ,以及如何在主应用程序中加载正确的信息,例如,如果我登录到用户1,我希望显示用户信息,并与其他用户相同。对不起,如果我严重解释自己。

3 个答案:

答案 0 :(得分:1)

如果您不需要复杂的Db,我认为如果您使用数据库的最佳方式,我认为SQLite非常适合您。

我建议,如果你想在xml中存储数据,你必须保存整个UserList,或者你可以将XML文件保存到用户临时文件夹Path.GetTempPath(),但只有当用户使用不同的Windows用户登录时才会知道。

答案 1 :(得分:0)

如上所述,最好的方法是使用SQL或至少将所有用户存储在一个xml文件中。但是,如果您确实需要将所有用户信息存储在单独的文件中,则可以仅为用户信息文件创建一些目录,并且每次登录或获取某些用户信息时,您应该迭代抛出所有文件并对每个文件进行反序列化。

类似的东西:

string[] files = Directory.GetFiles('your user storage directory'); 
foreach (string file in files) { 
  user = loadUser.loadData(file);
  //your logic goes here
}

答案 2 :(得分:0)

您的答案。
我已将用户信息保存在 xml 中并在表单加载时加载它。
将文件名保存为 test.xml
enter image description here

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;

namespace Login_Form
{
    public partial class Form1 : Form
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            saveFileDialog.Filter = "xml Files (*.xml)|*.xml";
            saveFileDialog.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(saveFileDialog.FileName))
                    File.Delete(saveFileDialog.FileName);

                User user = new User();
                user.FName = textBox1.Text;
                user.LName = textBox2.Text;
                user.Username = textBox3.Text;
                user.Email = textBox4.Text;
                user.Password = textBox5.Text;

                XmlWriter xmlWriter = XmlWriter.Create(saveFileDialog.FileName);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("UserInfo");

                xmlWriter.WriteStartElement("FName");
                xmlWriter.WriteString(user.FName);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("LName");
                xmlWriter.WriteString(user.LName);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Username");
                xmlWriter.WriteString(user.Username);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Email");
                xmlWriter.WriteString(user.Email);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("Password");
                xmlWriter.WriteString(user.Password);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Close();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            User user = new User();
            string filePath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            filePath += "\\test.xml";
            if (File.Exists(filePath))
            {
                XmlDocument doc = new XmlDocument();

                doc.Load(filePath);
                XmlNode VersionNode = null;
                VersionNode = doc.SelectSingleNode("UserInfo");
                if (null == VersionNode) return;
                user.FName = VersionNode.SelectSingleNode("FName").InnerText;
                user.LName = VersionNode.SelectSingleNode("LName").InnerText;
                user.Username = VersionNode.SelectSingleNode("Username").InnerText;
                user.Email = VersionNode.SelectSingleNode("Email").InnerText;
                user.Password = VersionNode.SelectSingleNode("Password").InnerText;

                textBox1.Text = user.FName;
                textBox2.Text = user.LName;
                textBox3.Text = user.Username;
                textBox4.Text = user.Email;
                textBox5.Text = user.Password;
            }
        }
    }

    public class User
    {
        private string fName;
        private string lName;
        private string username;
        private string email;
        private string password;

        public string FName
        {
            get { return fName; }
            set { fName = value; }
        }

        public string LName
        {
            get { return lName; }
            set { lName = value; }
        }

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        public string Email
        {
            get { return email; }
            set { email = value; }
        }

        public string Password
        {
            get { return password; }
            set { password = value; }
        }
    }
}