C#尝试将ArrayList序列化为XML文件

时间:2014-11-26 14:44:11

标签: c# xml serialization

struct ClientInfo
    {
        public string strName;  //Name by which the user logged into the chat room
        public string strPW;
    }

    ArrayList clientList = new ArrayList();

    public static void Serialize(ArrayList input)
    {
        XmlSerializer serializer = new XmlSerializer(input.GetType());
        TextWriter sw = new StreamWriter("users.txt");
        serializer.Serialize(sw, input);
        sw.Close();
    }

所以我试图在ArrayList中存储名称/密码组合,我试图将这个ArrayList保存到一个文件中,并在每次启动程序时加载它。但是,程序会在serializer.Serialize(sw, input);行停止,并显示以下内容:

  

未处理的类型' System.InvalidOperationException'发生在System.Xml.dll

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我们走了;我认为这解决了所有问题......

public class ClientInfo // you meant "class" right? since that clearly isn't a "value"
{
    public string Name {get;set;} // use a property; don't use a name prefix
    public string Password {get;set;} // please tell me you aren't storing passwords
}

List<ClientInfo> clientList = new List<ClientInfo>(); // typed list

public static void Serialize(List<ClientInfo> input) // typed list
{
    if(input == null) throw new ArgumentNullException("input");
    XmlSerializer serializer = new XmlSerializer(typeof(List<ClientInfo>));
    using(TextWriter sw = new StreamWriter("users.txt")) // because: IDisposable
    {
        serializer.Serialize(sw, input);
        sw.Close();
    }
}