Friday, March 29, 2013

C# Code to deserialize a Byte[] Array into DataTable


In WCF, sometimes we get a ByteArray as an output data contract and we want to deserialize that ByteArray into a DataTable.
Here we could get an idea how we can deserialize a ByteArray into DataTable.  DataTable becomes useful int the situations when we want to save data into database using DataAdapter by passing a DataSet.
In this code, we create a MemoryStream object by passing byte array and then using BinaryFormatter, we can directly deserialize MemoryStream object into DataTable.


 
 private DataSet DeserailizeByteArrayToDataSet(byte[] byteArrayData)  
     {  
       DataSet tempDataSet = new DataSet();  
       DataTable dt;  
       // Deserializing into datatable    
       using (MemoryStream stream = new MemoryStream(byteArrayData))  
       {  
         BinaryFormatter bformatter = new BinaryFormatter();  
         dt = (DataTable)bformatter.Deserialize(stream);  
         if (dt != null)  
         {  
           foreach (DataRow row in dt.Rows)  
           {  
             Console.WriteLine("----------------------");  
             Console.WriteLine("PostalCode:" + row["POSTAL_CODE"]);  
             Console.WriteLine("CountryCode:" + row["COUNTRY_CODE"]);  
             Console.WriteLine("ProcessNumber:" + row["PROCESS_NUMBER"]);  
             Console.WriteLine("ProcessStatus:" + row["PROCESS_STATUS"]);  
             Console.WriteLine("TimeStamp:" + row["TIMESTAMP"]);  
             Console.WriteLine("----------------------");  
           }  
         }  
       }  
       // Adding DataTable into DataSet    
       tempDataSet.Tables.Add(dt);  
       return tempDataSet;  
     }  







Thanks,
Hemant

No comments:

Post a Comment