Around and About .NET World

Il blog di Marco Minerva
posts - 1671, comments - 2232, trackbacks - 2135

My Links

News

Contattami su Live Messenger:


MCTS: Windows, Web, Distributed Applications & SQL Server

MCPD: Enterprise Applications

Tag Cloud

Archives

Post Categories

Links

Una classe helper per la formattazione binaria

Nelle mie applicazioni mi capita spesso di serializzare gli oggetti in formato binario per salvarli su disco, per inviarli sulla rete, ecc... Mi sono così definito una semplice classe helper per velocizzare questo procedimento:

using System; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace SerializationHelper { public static class Serializator { public static void Serialize(object obj, Stream serializationStream) { try { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(serializationStream, obj); } catch (SerializationException ex) { throw new SerializationException(ex.Message + Environment.NewLine + "To make a class serializable, add the 'Serializable' attribute before the declaration of the class.", ex.InnerException); } } public static void Serialize(object obj, string path) { using(Stream fileStream = File.Open(path, FileMode.Create)) Serialize(obj, fileStream); } public static object Deserialize(Stream serializationStream) { try { BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(serializationStream); } catch (SerializationException ex) { throw new SerializationException(ex.Message + Environment.NewLine + "To make a class serializable, add the 'Serializable' attribute before the declaration of the class.", ex.InnerException); } } public static object Deserialize(string path) { using(Stream fileStream = File.Open(path, FileMode.Open)) return Deserialize(fileStream); } } }

Non è niente di eccezionale, ma avere questo codice sempre a disposizione quando serve è molto comodo smile_wink.

Print | posted on Monday, January 29, 2007 10:31 PM | Filed Under [ C# ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET