write list of objects to a file

前端 未结 4 1167
既然无缘
既然无缘 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 00:53

    I just wrote a blog post on saving an object's data to Binary, XML, or Json; well writing an object or list of objects to a file that is. Here are the functions to do it in the various formats. See my blog post for more details.

    Binary

    /// 
    /// Writes the given object instance to a binary file.
    /// Object type (and all child types) must be decorated with the [Serializable] attribute.
    /// To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.
    /// 
    /// The type of object being written to the XML file.
    /// The file path to write the object instance to.
    /// The object instance to write to the XML file.
    /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file.
    public static void WriteToBinaryFile(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);
        }
    }
    
    /// 
    /// Reads an object instance from a binary file.
    /// 
    /// The type of object to read from the XML.
    /// The file path to read the object instance from.
    /// Returns a new instance of the object read from the binary file.
    public static T ReadFromBinaryFile(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

    Requires the System.Xml assembly to be included in your project.

    /// 
    /// Writes the given object instance to an XML file.
    /// Only Public properties and variables will be written to the file. These can be any type though, even other classes.
    /// If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.
    /// Object type must have a parameterless constructor.
    /// 
    /// The type of object being written to the file.
    /// The file path to write the object instance to.
    /// The object instance to write to the file.
    /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file.
    public static void WriteToXmlFile(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();
        }
    }
    
    /// 
    /// Reads an object instance from an XML file.
    /// Object type must have a parameterless constructor.
    /// 
    /// The type of object to read from the file.
    /// The file path to read the object instance from.
    /// Returns a new instance of the object read from the XML file.
    public static T ReadFromXmlFile(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

    You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

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

    Example

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

提交回复
热议问题