Wednesday, November 24, 2010

code for creating sql server table as a xml file

DataTable data_table = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from test_table", connection);
da.Fill(ds);
ds.WriteXml(@"c:\output2.xml", XmlWriteMode.IgnoreSchema);
connection.Close();


Read XML file data

XmlTextReader xml_reader = new XmlTextReader(@"c:\output1.xml");
        XmlDocument xml_doc = new XmlDocument();
        xml_doc.Load(xml_reader);
        XmlNode select_node = xml_doc.SelectSingleNode("NewDataSet");
        node_list = xml_doc.GetElementsByTagName("Table");

        for (i = 0; i < node_list.Count; i++)
        {
            for (j = 0; j < node_list[i].ChildNodes.Count; j++)
            {
                     Response.Write(node_list[i].ChildNodes[j].InnerText);
            }
}

code for zip and unzip the file using c#

using System.IO.Compression;
using System.IO;


Zip the File

 FileStream sourceFile = File.OpenRead(@"C:\output1.xml");
        FileStream destFile = File.Create(@"C:\sample.zip");

        GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

        try
        {
            int theByte = sourceFile.ReadByte();
            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }
        }
        finally
        {
            compStream.Dispose();
        }


UnZip the File

 string srcFile = @"C:\sample.zip";
        string dstFile = @"C:\file_xml1.xml";

        FileStream file_stream_in = null;
        FileStream file_stream_out = null;
        GZipStream zip = null;
        const int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];
        int count = 0;

        try
        {

            file_stream_in  = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            file_stream_out  = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
            zip = new GZipStream(file_stream_in , CompressionMode.Decompress, true);
            while (true)
            {
                count = zip.Read(buffer, 0, bufferSize);
                if (count != 0)
                {
                    file_stream_out.Write(buffer, 0, count);
                }
                if (count != bufferSize)
                {
                 
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        
            System.Diagnostics.Debug.Assert(false, ex.ToString());
        }