write list of objects to a file

前端 未结 4 1161
既然无缘
既然无缘 2020-12-01 00:11

I\'ve got a class salesman in the following format:

class salesman
{
    public string name, address, email;
    public int sales;
}

I\'ve

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 01:09

    If you want xml serialization, you can use the built-in serializer. To achieve this, add [Serializable] flag to the class:

    [Serializable()]
    class salesman
    {
        public string name, address, email;
        public int sales;
    }
    

    Then, you could override the "ToString()" method which converts the data into xml string:

    public override string ToString()
        {
            string sData = "";
            using (MemoryStream oStream = new MemoryStream())
            {
                XmlSerializer oSerializer = new XmlSerializer(this.GetType());
                oSerializer.Serialize(oStream, this);
                oStream.Position = 0;
                sData = Encoding.UTF8.GetString(oStream.ToArray());
            }
            return sData;
        }
    

    Then just create a method that writes this.ToString() into a file.

    UPDATE The mentioned above will serialize single entry as xml. If you need the whole list to be serialized, the idea would be a bit different. In this case you'd employ the fact that lists are serializable if their contents are serializable and use the serialization in some outer class.

    Example code:

    [Serializable()]
    class salesman
    {
        public string name, address, email;
        public int sales;
    }
    
    class salesmenCollection 
    {
       List salesmanList;
    
       public void SaveTo(string path){
           System.IO.File.WriteAllText (path, this.ToString());
       }    
    
       public override string ToString()
       {
         string sData = "";
         using (MemoryStream oStream = new MemoryStream())
          {
            XmlSerializer oSerializer = new XmlSerializer(this.GetType());
            oSerializer.Serialize(oStream, this);
            oStream.Position = 0;
            sData = Encoding.UTF8.GetString(oStream.ToArray());
          }
         return sData;
        }
    }
    

提交回复
热议问题