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<T>
{
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;
}
/// <summary>
/// Serializes objects to a SOAP .xml format
/// </summary>
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);
}
}
/// <summary>
/// Serializes objects to a Binary .txt format
/// </summary>
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);
}
}
/// <summary>
/// Deserializes a SOAP .xml file format
/// </summary>
/// <returns>Deserialized object</returns>
public T DeserializeSoapFormat()
{
try
{
SoapFormatter soapFormatter = new SoapFormatter();
Stream dataStream = File.OpenRead(_filePath + _fileName);
T result = (T)soapFormatter.Deserialize(dataStream);
dataStream.Close();
return result;
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}
/// <summary>
/// Deserializes a Binary .txt file format
/// </summary>
/// <returns>Deserialized object</returns>
public T DeserializeBinaryFormat()
{
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
Stream dataStream = File.OpenRead(_filePath + _fileName);
T result = (T)binaryFormatter.Deserialize(dataStream);
dataStream.Close();
return result;
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}
}
}