将对象列表写入文件

本文关键字:文件 列表 对象 | 更新日期: 2023-09-27 18:11:51

我有一个class sales,格式如下:

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

我有另一个类,其中用户输入姓名、地址、电子邮件和销售额。然后将此输入添加到列表

List<salesman> salesmanList = new List<salesman>();

在用户向列表中输入了尽可能多的销售人员之后,他们可以选择将列表保存到他们选择的文件中(我可以将其限制为.xml或.txt(哪个更合适))。如何将这个列表添加到文件中?此外,如果用户希望稍后查看记录,则需要将该文件重新读入列表。

将对象列表写入文件

这样就可以了。它使用二进制格式(加载速度最快),但相同的代码将适用于具有不同序列化器的XML。

using System.IO;
    [Serializable]
    class salesman
    {
        public string name, address, email;
        public int sales;
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<salesman> salesmanList = new List<salesman>();
            string dir = @"c:'temp";
            string serializationFile = Path.Combine(dir, "salesmen.bin");
            //serialize
            using (Stream stream = File.Open(serializationFile, FileMode.Create))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bformatter.Serialize(stream, salesmanList);
            }
            //deserialize
            using (Stream stream = File.Open(serializationFile, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                List<salesman>  salesman = (List<salesman>)bformatter.Deserialize(stream);
            }
        }
    }

我刚刚写了一篇关于将对象数据保存为二进制、XML或Json的博客文章;写一个对象或者对象列表到文件中。下面是各种格式的函数。更多细节请看我的博客。

二进制
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}
XML

要求将System.Xml程序集包含在项目中。

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}
Json

必须包含对Newtonsoft的引用。Json程序集,可以从Json中获得。. NET NuGet Package.

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
        writer = new StreamWriter(filePath, append);
        writer.Write(contentsToWriteToFile);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

// Write the list of salesman objects to file.
WriteToXmlFile<List<salesman>>("C:'salesmen.txt", salesmanList);
// Read the list of salesman objects from the file back into a variable.
List<salesman> salesmanList = ReadFromXmlFile<List<salesman>>("C:'salesmen.txt");

如果你想使用JSON,那就使用JSON。. NET通常是最好的方法。

如果因为某些原因你不能使用Json。你可以使用。NET中内置的JSON支持。

您需要包含以下using语句,并为 system . web . extensions .

添加一个引用
using System.Web.Script.Serialization;

然后你可以使用这些来序列化和反序列化你的对象。

//Deserialize JSON to your Object
YourObject obj = new JavaScriptSerializer().Deserialize<YourObject>("File Contents");
//Serialize your object to JSON
string sJSON = new JavaScriptSerializer().Serialize(YourObject);

https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer_methods (v = vs.110) . aspx

如果需要xml序列化,可以使用内置的序列化器。要实现这一点,在类中添加[Serializable]标志:

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

然后,你可以重写"ToString()"方法,它将数据转换为xml字符串:

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;
    }

然后创建一个方法,将this.ToString()写入文件。

更新上面提到的代码将把单个条目序列化为xml。如果您需要序列化整个列表,那么想法就有点不同了。在这种情况下,如果列表的内容是可序列化的,那么列表就是可序列化的,并在某些外部类中使用序列化。

示例代码:

[Serializable()]
class salesman
{
    public string name, address, email;
    public int sales;
}
class salesmenCollection 
{
   List<salesman> 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;
    }
}