AA2Install.GZip.CompressString C# (CSharp) Method

CompressString() public static method

Compresses a string in the UTF-8 format.
public static CompressString ( string str ) : byte[]
str string String to compress.
return byte[]
        public static byte[] CompressString(string str)
        {
            var bytes = Encoding.UTF8.GetBytes(str);

            using (var msi = new MemoryStream(bytes))
                using (var mso = new MemoryStream())
                {
                    using (var gs = new GZipStream(mso, CompressionMode.Compress))
                        msi.CopyTo(gs);

                    return mso.ToArray();
                }
        }

Usage Example

Ejemplo n.º 1
0
        /// <summary>
        /// Writes a setting to the configuration.
        /// </summary>
        /// <param name="key">Key of item to write.</param>
        /// <param name="value">Value of item to write.</param>
        /// <returns>True if successful, otherwise false.</returns>
        public static bool WriteSetting(string key, string value)
        {
            try
            {
                key = key.ToLower();
                Trace.WriteLine(key + " : " + value);
                string json = "";
                if (File.Exists(Paths.CONFIG + ".gz"))
                {
                    //json = File.ReadAllText(Paths.CONFIG);
                    json = GZip.DecompressString(File.ReadAllBytes(Paths.CONFIG + ".gz"));
                }
                var settings = JsonConvert.DeserializeObject <SerializableDictionary <string, string> >(json);
                if (settings == null)
                {
                    settings = new SerializableDictionary <string, string>();
                }
                settings[key] = value;

                //File.WriteAllText(Paths.CONFIG, JsonConvert.SerializeObject(settings));
                File.WriteAllBytes(Paths.CONFIG + ".gz", GZip.CompressString(JsonConvert.SerializeObject(settings)));
                return(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error writing app settings: " + ex.Message);
                return(false);
            }
        }