using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
namespace IpTerm
{
//版权所有: jhabb 邮箱:jhabb@163.com// qq :75420724 欢迎讨论 转载请标明
public class Usermanager
{
private List<User> users = new List<User>();
/// <summary>
/// 构造函数
/// </summary>
[XmlElement("Users")]
public List<User> Users
{
get { return users; }
set { users = value; }
}
/// <summary>
/// 反序列化
/// </summary>
public void Load(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return; }
TextReader textReader = null;
XmlSerializer serial = null;
Usermanager manager = null;
if (!File.Exists(fileName)) { Save(fileName); return; }
try
{
textReader = new StreamReader(fileName);
serial = new XmlSerializer(this.GetType());
manager = serial.Deserialize(textReader) as Usermanager;
textReader.Close();
foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
{
if (propertyInfo.CanWrite)
{
object value = this.GetType().GetProperty(propertyInfo.Name).GetValue(manager, null);
propertyInfo.SetValue(this, value, null);
}
}
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
finally
{
if (textReader != null) { textReader.Close(); }
}
}
/// <summary>
/// 序列化
/// </summary>
public void Save(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return; }
string directoryName = Path.GetDirectoryName(fileName);
if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
{
DirectoryInfo dirInfo;
try
{
dirInfo = Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
return;
}
}
TextWriter textWriter = null;
XmlSerializer serial = null;
try
{
textWriter = new StreamWriter(fileName);
serial = new XmlSerializer(this.GetType());
serial.Serialize(textWriter, this);
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
finally
{
if (textWriter != null) { textWriter.Close(); }
}
}
}
public class User
{
private string user_name;
[XmlAttribute("User_name")]
public string User_name
{
get { return user_name; }
set { user_name = value; }
}
private string user_IP;
[XmlAttribute("User_IP")]
public string User_IP
{
get { return user_IP; }
set { user_IP = value; }
}
private string user_port;
[XmlAttribute("User_port")]
public string User_port
{
get { return user_port; }
set { user_port = value; }
}
/// <summary>
/// 构造函数
/// </summary>
public User()
{
}
}
}