如何快速保存/加载类实例到文件

我的应用程序中有几个类/结构集合。

该类只是一个带有字段的类

class A { public int somevalue; public string someothervalue } 

还有我的collections

 List _myList; 

我需要能够保存_myList并加载。 我只想将所有类字段保存到文件和加载。 我不想花时间写自己的保存/加载。 .NET中是否有任何工具可以帮助我。 我不关心文件格式。

我刚写了一篇关于将对象数据保存到Binary,XML或Json的博客文章 ; 将对象或对象列表写入文件。 以下是以各种格式执行此操作的function。 有关详细信息,请参阅我的博文。

二进制

 ///  /// 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

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

 ///  /// 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

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

 ///  /// 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(); } } 

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

有许多序列化器:

.net框架的一部分

  • XmlSerializer(标准格式,慢和冗长)
  • BinarySerializer(专有格式,中速, 支持循环图 ,序列化字段而不是属性=> 恼人的版本控制

第三方:

  • Json-Serializers(标准化格式,基于文本,短于xml)
  • ProtoBuf-Serializers(标准化格式,二进制,非常快)

如果文件可能是二进制文件,我可能会使用ProtoBuf Serializer,如果需要是纯文本,我可能会使用json序列化程序。

您可以使用XML序列化程序或二进制序列化程序序列化List<> ,并将序列化列表保存到文件中。

稍后,您可以阅读此文件内容并检索原始列表。

创建要为其创建列表的类型[Serializable]

我通常使用XML Serilizer,快速,易于实现并以可读的方式保持对象,你可以看到一个很好的例子 。

如果需要更有效的更大规模的解决方案,可以使用二进制序列化。 (例如,如果要通过网络传输序列化。)

编辑:要获得对序列化元素的更多控制,请查看此示例

旧主题,但我修改了Tim Coker上面的答案,利用using块来正确处理流对象,并且一次只保存一个类实例:

 public static T Load(string FileSpec) { XmlSerializer formatter = new XmlSerializer(typeof(T)); using (FileStream aFile = new FileStream(FileSpec, FileMode.Open)) { byte[] buffer = new byte[aFile.Length]; aFile.Read(buffer, 0, (int)aFile.Length); using (MemoryStream stream = new MemoryStream(buffer)) { return (T)formatter.Deserialize(stream); } } } public static void Save(T ToSerialize, string FileSpec) { Directory.CreateDirectory(FileSpec.Substring(0, FileSpec.LastIndexOf('\\'))); FileStream outFile = File.Create(FileSpec); XmlSerializer formatter = new XmlSerializer(typeof(T)); formatter.Serialize(outFile, ToSerialize); }