如何快速保存/加载类实例到文件
我的应用程序中有几个类/结构集合。
该类只是一个带有字段的类
class A { public int somevalue; public string someothervalue }
还有我的collections
List _myList;
我需要能够保存_myList并加载。 我只想将所有类字段保存到文件和加载。 我不想花时间写自己的保存/加载。 .NET中是否有任何工具可以帮助我。 我不关心文件格式。
XMLSerializer并不难使用。 只要你的物体不是很大,它就会很快。 我在一些应用程序中序列化了一些巨大的对象。 它需要永远,结果文件几乎100兆,但如果我需要调整一些东西,它们是可编辑的。 另外,如果我向对象添加字段也没关系。 旧版本对象的序列化文件仍然正确反序列化。我在一个单独的线程上进行序列化,所以在我的情况下需要多长时间。 需要注意的是,您的A
类必须具有XMLSerialziation的构造函数才能工作。
这里有一些工作代码用于序列化/反序列化,error handling被撕掉以便于阅读……
private List Load() { string file = "filepath"; List listofa = new List(); XmlSerializer formatter = new XmlSerializer(A.GetType()); FileStream aFile = new FileStream(file, FileMode.Open); byte[] buffer = new byte[aFile.Length]; aFile.Read(buffer, 0, (int)aFile.Length); MemoryStream stream = new MemoryStream(buffer); return (List)formatter.Deserialize(stream); } private void Save(List listofa) { string path = "filepath"; FileStream outFile = File.Create(path); XmlSerializer formatter = new XmlSerializer(A.GetType()); formatter.Serialize(outFile, listofa); }
我刚写了一篇关于将对象数据保存到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
有许多序列化器:
.net框架的一部分
第三方:
如果文件可能是二进制文件,我可能会使用ProtoBuf Serializer,如果需要是纯文本,我可能会使用json序列化程序。
您可以使用XML序列化程序或二进制序列化程序序列化List<>
,并将序列化列表保存到文件中。
稍后,您可以阅读此文件内容并检索原始列表。
创建要为其创建列表的类型[Serializable]
我通常使用XML Serilizer,快速,易于实现并以可读的方式保持对象,你可以看到一个很好的例子 。
如果需要更有效的更大规模的解决方案,可以使用二进制序列化。 (例如,如果要通过网络传输序列化。)
编辑:要获得对序列化元素的更多控制,请查看此示例
旧主题,但我修改了Tim Coker上面的答案,利用using块来正确处理流对象,并且一次只保存一个类实例:
上述就是C#学习教程:如何快速保存/加载类实例到文件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000441.html