.net - Serialize Entity Framework object, save to file, read and DeSerialize -
the title should make clear i'm trying - entity framework object, serialize string, save string in file, load text file , reserialize object. hey presto!
but of course doesn't work else wouldn't here. when try reserialise "the input stream not in valid binary format" error i'm missing somewhere.
this how serialise , save data:
string filepath = system.configuration.configurationmanager.appsettings["customerslitesavepath"]; string filename = system.configuration.configurationmanager.appsettings["customerslitefilename"]; if(file.exists(filepath + filename)) { file.delete(filepath + filename); } memorystream memorystream = new memorystream(); binaryformatter binaryformatter = new binaryformatter(); binaryformatter.serialize(memorystream, entityframeworkquery.first()); string str = system.convert.tobase64string(memorystream.toarray()); streamwriter file = new streamwriter(filepath + filename); file.writeline(str); file.close();
which gives me big nonsensical text file, you'd expect. try , rebuild object elsewhere:
customerobject = file.readalltext(path); memorystream ms = new memorystream(); filestream fs = new filestream(path, filemode.open); int bytesread; int blocksize = 4096; byte[] buffer = new byte[blocksize]; while (!(fs.position == fs.length)) { bytesread = fs.read(buffer, 0, blocksize); ms.write(buffer, 0, bytesread); } binaryformatter formatter = new binaryformatter(); ms.position = 0; customer cust = (customer)formatter.deserialize(ms);
and binary format error.
i'm being stupid. in way?
cheers, matt
when you've saved it, have (for reasons best known you) applied base-64 - haven't applied base-64 when reading it. imo, drop base-64 - , write directly filestream
. saves having buffer in memory.
for example:
if(file.exists(path)) { file.delete(path); } using(var file = file.create(path)) { binaryformatter ser = new binaryformatter(); ser.serialize(file, entityframeworkquery.first()); file.close(); }
and
using(var file = file.openread(path)) { binaryformatter ser = new binaryformatter(); customer cust = (customer)ser.deserialize(file); ... }
as side note, may find datacontractserializer
makes better serializer ef binaryformatter
.
Comments
Post a Comment