Saturday, September 6, 2014

Store bytes conent to zip file in C#



You can store bytes in zip using the GZipStream object.

 
public static void CreateZipFromBytes(string fileName, byte[] bytesToCompress)

        {

            using (FileStream fileToCompress = File.Create(fileName))

            {

                using (GZipStream compressionStream = new GZipStream(fileToCompress, CompressionMode.Compress))

                {

                    compressionStream.Write(bytesToCompress, 0, bytesToCompress.Length);

                }

            }

        }

Serialize object to XML with custom object with indentation


Serialize object to XML with custom object with indentation 


If you want to serialize object without including the tag XMLInclude and with nice indentation and formatting use the below method  

 

public static String SerializeObject(object objectToSerialize, List<Type> knownTypes)

        {

            XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType(), knownTypes.ToArray());

            var stringBuilder = new StringBuilder();

            var xmlTextWriter = XmlTextWriter.Create(stringBuilder, new XmlWriterSettings { NewLineChars = "\r\n", Indent = true });

            xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);

            return stringBuilder.ToString();

        }


Happy programming :)