HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Persist data by serializing/deserializing objects that are sent to it

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
objectsserializingaresentthatpersistdeserializingdata

Problem

I've created the following class to persist data by serializing/deserializing objects that are sent to it. I would like to know if there is a better way of writing this class, or if my class is fine the way it is.

```
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace Education_PersistingData
{
public class PersistData
{
private readonly T _obj;
private readonly string _filePath;
private readonly string _fileName;

public PersistData(T obj, string filePath, string fileName)
{
this._obj = obj;
this._filePath = filePath;
this._fileName = fileName;
}

///
/// Serializes objects to a SOAP .xml format
///
public void SerializeToSoapFormat()
{
try
{
SoapFormatter soapFormatter = new SoapFormatter();
Stream dataStream = File.Create(_filePath + _fileName);
soapFormatter.Serialize(dataStream, _obj);
dataStream.Close();
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}

///
/// Serializes objects to a Binary .txt format
///
public void SerializeToBinaryFormat()
{
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
Stream dataStream = File.Create(_filePath + _fileName);
binaryFormatter.Serialize(dataStream, _obj);
dataStream.Close();
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}

///
/// Deserializes a SOAP .xml file format
///
/// Deserialized object
public T DeserializeSoapFormat()
{
try
{
SoapFormatter soapFormatter = new SoapFormatter();
Stream dataStream = File.OpenRead(_filePath + _fileName);
T result = (T)soapFormatter.Deserialize(dataStream);

Solution

There is no point in catching the IOException and then throwing a new exception. You only loose information here. Either handle it or remove the try-catch altogether.

Also, use using to always dispose IDisposable objects.

Context

StackExchange Code Review Q#3432, answer score: 7

Revisions (0)

No revisions yet.