如何将一个类的对象保存到文件并重新加载它. [英] How to save object of a class to a file and reload it...........
问题描述
如何将类的对象保存到文件中.
像--->
classname obj = new classname();
然后如何将obj保存到文件中以备将来使用.
How to save object of a class to a file.
like --->
classname obj=new classname();
then how to save obj to a file for future use.
and then how to read data back from file in object.
推荐答案
可以使用Serializeand Deserialize概念解决问题.
看到这1st你应该有命名空间
U r problem can be solver using Serializeand Deserialize concept
see this 1st u should have namespaces
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
然后创建一个类
then create a class
[Serializable]
class Class1
{
public string name;
public string ID;
public string address;
}
可序列化是我们需要使用的关键词
然后在主程序中编写此代码
BinaryFormatter bnf = new BinaryFormatter();
MemoryStream ms =新的MemoryStream();
Class1 obj =新的Class1();
obj.name =阿伦";
obj.ID ="007";
obj.address ="Mysore";
bnf.Serialize(ms,obj);
byte [] obj_content = ms.ToArray();
//File.Create("C:\\arun.arv);
//File.WriteAllBytes("C:\\arun.arv,obj_content);
FileStream fs1 = new FileStream("C:\\ arun.arv",FileMode.Create);
BinaryWriter写入=新的BinaryWriter(fs1);
write.Write(obj_content);
write.Close();
fs1.Close();
FileStream fs = new FileStream("C:\\ arun.arv",FileMode.Open);
BinaryReader read = new BinaryReader(fs);
byte [] obj_converter =新的byte [fs.Length];
read.Read(obj_converter,0,obj_converter.Length);
MemoryStream ms1 =新的MemoryStream(obj_converter);
BinaryFormatter bnf1 =新的BinaryFormatter();
ms1.Position = 0;
Class1 obj2 =(Class1)bnf1.Deserialize(ms1);
Console.Write(obj2.name);
Console.Write(obj2.ID);
Console.Write(obj2.address);
Serializable is a key word we need to use it
then in main program write this code
BinaryFormatter bnf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
Class1 obj = new Class1();
obj.name = "Arun";
obj.ID = "007";
obj.address="Mysore";
bnf.Serialize(ms, obj);
byte[] obj_content = ms.ToArray();
//File.Create("C:\\arun.arv");
//File.WriteAllBytes("C:\\arun.arv", obj_content);
FileStream fs1 = new FileStream("C:\\arun.arv", FileMode.Create);
BinaryWriter write = new BinaryWriter(fs1);
write.Write(obj_content);
write.Close();
fs1.Close();
FileStream fs = new FileStream("C:\\arun.arv",FileMode.Open);
BinaryReader read=new BinaryReader (fs);
byte[] obj_converter = new byte[fs.Length];
read.Read(obj_converter, 0, obj_converter.Length);
MemoryStream ms1 = new MemoryStream(obj_converter);
BinaryFormatter bnf1 = new BinaryFormatter();
ms1.Position = 0;
Class1 obj2 = (Class1)bnf1.Deserialize(ms1);
Console.Write(obj2.name);
Console.Write(obj2.ID);
Console.Write(obj2.address);
如果要序列化的类未标记为[Serializable]
,则可以使用
If the class you want to serialize isn''t marked with [Serializable]
, you can use XmlSerializer.
尝试
这篇关于如何将一个类的对象保存到文件并重新加载它.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!