Wednesday, December 24, 2008

.NET Object Serialization and Deserialization

#region using
using System;
using System.Xml.Serialization;
using System.IO;
#endregion using

namespace Utilities
{
// Serializes and deserializes objects into and from xml document.
public static class Serializer
{
#region Public Methods

// Serializes the supplied object into specified xml document.
public static void SerializeObject( string fileName, T objectToSerialize )
{
using ( TextWriter writer = new StreamWriter( fileName ) )
{
XmlSerializer serializer = new XmlSerializer( typeof( T ) );
serializer.Serialize( writer, objectToSerialize );
}
}

// Deserializes the specified object from supplied xml document.
public static T DeserializeObject( string fileName )
{
// Create object to be deserialized.
T objectToDeserialize = (T)Activator.CreateInstance( typeof(T) );

if ( File.Exists( fileName ) )
{
// Deserialize object from xml file.
using ( TextReader reader = new StreamReader( fileName ) )
{
XmlSerializer serializer = new XmlSerializer( typeof(T) );
objectToDeserialize = (T)serializer.Deserialize( reader );
}
}

return objectToDeserialize;
}

#endregion Public Methods
}
}

ExcelReader - Reading a Microsoft Excel file in C#

#region using
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;

using Microsoft.Office.Interop.Excel;
#endregion using

namespace Utilities
{
// Represents a reader for MS Excel file (.XLS).
public class ExcelReader
{
private Application excelApp = null;
private Workbook workbook = null;
private string filePath = string.Empty;

#region Public Methods

// Opens the specified excel file and returns the workbook.
public Workbook OpenFile( string filePath )
{
if ( File.Exists( filePath ) )
{
this.excelApp = new ApplicationClass();
this.filePath = filePath;
Missing missing = Missing.Value;

this.workbook = this.excelApp.Workbooks.Open( filePath,
missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing,
missing, missing );
}

return this.workbook;
}

// Closes the opened excel file.
public void Close()
{
if ( this.workbook != null )
{
// Release the excel COM objects, setup the garbage collector for cleanup.
this.workbook.Close( false, this.filePath, false );
this.excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject( this.workbook );
System.Runtime.InteropServices.Marshal.ReleaseComObject( this.excelApp );
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

#endregion Public Methods
}
}