I’m using : boito = Serializer.DeSerializeObject("XOPC.xml"); with try catch.
so here is method :
public static ObjectToSerialize DeSerializeObject(string filename)
{
ObjectToSerialize objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
I had changed structure and it’s failing to DeSerialize this file but on next step when I’m trying to serialize it again I’m getting error : “This file is using by another process” and I can’t access it.
So how to stop using file after error in deserialization ?
You’re not closing the stream if an exception is thrown. Use a
usingstatement:This is equivalent to disposing of the stream in a
finallyblock.This isn’t just about deserialization – you should (almost1) always use
usingstatements for unmanaged resources. Any explicit call toCloseorDispose(outside aDisposeimplementation merely releasing composed resources) is suspicious.1 Very occasionally you want to leave a resource open on success, but close it if something else fails. This is rare and awkward.