Po wpisaniu "objectoutputstream c#’ do Google wypluło mi coś takiego jak BinaryFormatter, który robi mniej więcej to samo. Był też taki przykład:
string fileName = Path.GetTempFileName();
FileInfo fileInfo = new FileInfo(fileName);
// Write the current time to the file in binary form.
DateTime currentTime = DateTime.Now;
FileStream fileWriteStream = fileInfo.OpenWrite();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileWriteStream, currentTime);
fileWriteStream.Close();
// Read the time back from the file.
FileStream fileReadStream = fileInfo.OpenRead();
DateTime timeRead = (DateTime)binaryFormatter.Deserialize(fileReadStream);
fileReadStream.Close();
Console.WriteLine("Value written {0}", currentTime);
Console.WriteLine("Value read {0}", timeRead);
Klasa, która będzie podlegać serializacji, musi być oznaczona atrybutem [serializable]. Serializowane są tylko te pola klasy, które oznaczone są jako publiczne (public). Przykład:
[Serializable]
public class SomeClass
{
public string SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
}
W kodzie, w którym użyjesz poniższych funkcji, musisz zadeklarować następujące przestrzenie nazw:
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = null;
MemoryStream ms = null;
try
{
bf = new BinaryFormatter();
ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (ms != null)
ms.Close();
}
}
public static object ByteArrayToObject(byte[] arrBytes)
{
if (arrBytes == null)
return null;
BinaryFormatter bf = null;
MemoryStream ms = null;
try
{
bf = new BinaryFormatter();
ms = new MemoryStream();
ms.Write(arrBytes, 0, arrBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(ms);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (ms != null)
ms.Close();
}
}