Write() public méthode

Write data to the stream.

If you wish to use the GZipStream to compress data while writing, you can create a GZipStream with CompressionMode.Compress, and a writable output stream. Then call Write() on that GZipStream, providing uncompressed data as input. The data sent to the output stream will be the compressed form of the data written.

A GZipStream can be used for Read() or Write(), but not both. Writing implies compression. Reading implies decompression.

public Write ( byte buffer, int offset, int count ) : void
buffer byte The buffer holding data to write to the stream.
offset int the offset within that data array to find the first byte to write.
count int the number of bytes to write.
Résultat void
        /// <summary>
        /// Compresses the file at the given path. Returns the path to the
        /// compressed file.
        /// </summary>
        /// <param name="path">The path to compress.</param>
        /// <returns>The path of the compressed file.</returns>
        public string Compress(string path)
        {
            string outputPath = String.Concat(path, ".gz");

            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            using (FileStream fs = File.OpenRead(path))
            {
                using (FileStream output = File.Create(outputPath))
                {
                    using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, CompressionLevel.BestCompression))
                    {
                        byte[] buffer = new byte[4096];
                        int count = 0;

                        while (0 < (count = fs.Read(buffer, 0, buffer.Length)))
                        {
                            gzip.Write(buffer, 0, count);
                        }
                    }
                }
            }

            return outputPath;
        }
        /// <summary>
        /// 지정된 데이타를 압축한다.
        /// </summary>
        /// <param name="input">압축할 Data</param>
        /// <returns>압축된 Data</returns>
        public override byte[] Compress(byte[] input) {
            if(IsDebugEnabled)
                log.Debug(CompressorTool.SR.CompressStartMsg);

            // check input data
            if(input.IsZeroLength()) {
                if(IsDebugEnabled)
                    log.Debug(CompressorTool.SR.InvalidInputDataMsg);

                return CompressorTool.EmptyBytes;
            }

            byte[] output;

            using(var outStream = new MemoryStream(input.Length)) {
                using(var gzip = new GZipStream(outStream, CompressionMode.Compress)) {
                    gzip.Write(input, 0, input.Length);
                }
                output = outStream.ToArray();
            }

            if(IsDebugEnabled)
                log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length);

            return output;
        }
    void CompressFile(string Source, string Destination)
    {
        Log(" Compressing " + Source);
        bool DeleteSource = false;

        if (Source == Destination)
        {
            string CopyOrig = Source + ".Copy";
            File.Copy(Source, CopyOrig);
            Source       = CopyOrig;
            DeleteSource = true;
        }

        using (System.IO.Stream input = System.IO.File.OpenRead(Source))
        {
            using (var raw = System.IO.File.Create(Destination))
            {
                using (Stream compressor = new Ionic.Zlib.GZipStream(raw, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression))
                {
                    byte[] buffer   = new byte[2048];
                    int    SizeRead = 0;
                    while ((SizeRead = input.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        compressor.Write(buffer, 0, SizeRead);
                    }
                }
            }
        }

        if (DeleteSource)
        {
            File.Delete(Source);
        }
    }
        static public byte[] compress(byte[] bytes)
        {

            var output = new MemoryStream();
            var gzipStream = new GZipStream(output, CompressionMode.Compress, true);
            gzipStream.Write(bytes, 0, bytes.Length);
            gzipStream.Close();
            return output.ToArray();

        }
Exemple #5
0
 public static void Compress(byte[] data, string path)
 {
     using (GZipStream gzip = new GZipStream(
         new FileStream(path, FileMode.Create, FileAccess.Write),
         CompressionMode.Compress, CompressionLevel.BestCompression,
         false))
     {
         gzip.Write(data, 0, data.Length);
         gzip.Flush();
     }
 }
        public static byte[] CompressGzip(byte[] bytes)
        {
            using (var ms = new MemoryStream())
            {
                using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    zip.Write(bytes, 0, bytes.Length);
                }

                return ms.ToArray();
            }
        }
Exemple #7
0
 public static byte[] Compress(byte[] data)
 {
     MemoryStream output = new MemoryStream();
     using (GZipStream gzip = new GZipStream(
         output,
         CompressionMode.Compress,
         CompressionLevel.BestCompression,
         true))
     {
         gzip.Write(data, 0, data.Length);
         gzip.Flush();
     }
     return output.ToArray();
 }
Exemple #8
0
 public static void ZipStreamCompress(Stream source, Stream dest)
 {
     using (var stream = new Ionic.Zlib.GZipStream(
                dest,
                Ionic.Zlib.CompressionMode.Compress,
                Ionic.Zlib.CompressionLevel.BestCompression,
                true))
     {
         byte[] buf = new byte[ZIP_BUFFER_SIZE];
         int    len;
         while ((len = source.Read(buf, 0, buf.Length)) > 0)
         {
             stream.Write(buf, 0, len);
         }
     }
 }
Exemple #9
0
        public static byte[] DeflateByte(byte[] str)
        {
            if (str == null)
            {
                return(null);
            }

            using (var output = new MemoryStream())
            {
                using (var compressor = new Ionic.Zlib.GZipStream(output, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }
                return(output.ToArray());
            }
        }
        /// <summary>Creates a GZip stream by the given serialized object.</summary>
        private static Stream CreateGZipStream(string serializedObject)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(serializedObject);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    gzip.Write(bytes, 0, bytes.Length);
                }

                // Reset the stream to the beginning. It doesn't work otherwise!
                ms.Position = 0;
                byte[] compressed = new byte[ms.Length];
                ms.Read(compressed, 0, compressed.Length);
                return new MemoryStream(compressed);
            }
        }
Exemple #11
0
 /// <summary>
 /// 对byte数组进行压缩
 /// </summary>
 /// <param name="data">待压缩的byte数组</param>
 /// <returns>压缩后的byte数组</returns>
 public static byte[] Compress(byte[] data)
 {
     try
     {
         MemoryStream ms  = new MemoryStream();
         GZipStream   zip = new GZipStream(ms, CompressionMode.Compress, true);
         zip.Write(data, 0, data.Length);
         zip.Close();
         byte[] buffer = new byte[ms.Length];
         ms.Position = 0;
         ms.Read(buffer, 0, buffer.Length);
         ms.Close();
         return(buffer);
     }
     catch (IOException e)
     {
         throw new IOException(e.Message);
     }
 }
Exemple #12
0
        public void GZipStreamTest()
        {
            string testString = "Some testing string to compress/decompress using the GzipStream object!";

            // compress.
            var testStringBytes = ASCIIEncoding.ASCII.GetBytes(testString);
            var compressedStream = new MemoryStream();
            var stream = new GZipStream(compressedStream, CompressionMode.Compress);
            stream.Write(testStringBytes, 0, testStringBytes.Length);
            stream.Flush();
            byte[] compressedTestString = compressedStream.ToArray();

            // decompress.
            compressedStream = new MemoryStream(compressedTestString);
            var decompressiongStream = new GZipStream(compressedStream, CompressionMode.Decompress);
            var decompressedStream = new MemoryStream();
            decompressiongStream.CopyTo(decompressedStream);
            var decompressedTestString = new byte[decompressedStream.Length];
            decompressedStream.Read(decompressedTestString, 0, decompressedTestString.Length);

            ASCIIEncoding.ASCII.GetString(decompressedTestString);
        }
Exemple #13
0
 private byte[] Compress(byte[] bytes)
 {
     if (this._compression.ToLower() == "gzip")
     {
         using (MemoryStream memory = new MemoryStream())
         {
             using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
             {
                 gzip.Write(bytes, 0, bytes.Length);
             }
             return memory.ToArray();
         }
     }
     if (this._compression.ToLower() == "deflate")
     {
         using (MemoryStream memory = new MemoryStream())
         {
             using (ZlibStream deflate = new ZlibStream(memory, CompressionMode.Compress, true))
             {
                 deflate.Write(bytes, 0, bytes.Length);
             }
             return memory.ToArray();
         }
     }
     //no compression
     return bytes;
 }
    void CompressFile(string Source, string Destination)
    {
        Log(" Compressing " + Source);
        bool DeleteSource = false;

        if(  Source == Destination )
        {
            string CopyOrig = Source + ".Copy";
            File.Copy(Source, CopyOrig);
            Source = CopyOrig;
            DeleteSource = true;
        }

        using (System.IO.Stream input = System.IO.File.OpenRead(Source))
        {
            using (var raw = System.IO.File.Create(Destination))
                {
                    using (Stream compressor = new Ionic.Zlib.GZipStream(raw, Ionic.Zlib.CompressionMode.Compress,Ionic.Zlib.CompressionLevel.BestCompression))
                    {
                        byte[] buffer = new byte[2048];
                        int SizeRead = 0;
                        while ((SizeRead = input.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            compressor.Write(buffer, 0, SizeRead);
                        }
                    }
                }
        }

        if (DeleteSource && File.Exists(Source))
        {
            File.Delete(Source);
        }
    }
Exemple #15
0
        public byte[] Save()
        {
			//Save world to memory
			MemoryStream bytesStream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(bytesStream);
			
            Save(bw, false);
            tileManager.Save(bw);
            itemManager.Save(bw);
            avatarManager.Save(bw);
            sectorManager.Save(bw);
            dayCycleManager.Save(bw);

            bw.Flush();
			
			byte[] bytes = bytesStream.ToArray();
			
			//Write header
            MemoryStream bytesStreamFinal = new MemoryStream();
            BinaryWriter bwFinal = new BinaryWriter(bytesStreamFinal);

            bwFinal.Write(VERSION_INFO);
			bwFinal.Write(bytes.Length);
			bwFinal.Flush();
			
			//Compress and write world
			GZipStream gzipStream = new GZipStream(bytesStreamFinal, CompressionMode.Compress, CompressionLevel.BestSpeed, true);
			gzipStream.Write(bytes, 0, bytes.Length);
			gzipStream.Close();

            return bytesStreamFinal.ToArray();
        }
Exemple #16
0
 /// <summary>
 /// Compresses a byte array using the specified compression type.
 /// </summary>
 /// <param name="bytes">The byte array to be compressed.</param>
 /// <param name="level">Amount of compression to use.</param>
 /// <param name="type">Type of compression to use.</param>
 /// <returns>Compressed byte array.</returns>
 public static byte[] Compress(this byte[] bytes, CompressionLevel level, CompressionType type)
 {
     using (MemoryStream memory = new MemoryStream())
     {
         switch (type) {
             case CompressionType.Zlib:
                 using (ZlibStream stream = new ZlibStream(memory, CompressionMode.Compress, level, true))
                     stream.Write(bytes, 0, bytes.Length);
                 break;
             case CompressionType.GZip:
                 using (GZipStream stream = new GZipStream(memory, CompressionMode.Compress, level, true))
                     stream.Write(bytes, 0, bytes.Length);
                 break;
             default:
                 throw new ArgumentException("Unknown compression type.");
         }
         memory.Position = 0;
         bytes = new byte[memory.Length];
         memory.Read(bytes, 0, (int)memory.Length);
     }
     return bytes;
 }
Exemple #17
0
        public void Zlib_GZipStream_FileName_And_Comments()
        {
            // select the name of the zip file
            string FileToCompress = System.IO.Path.Combine(TopLevelDir, "Zlib_GZipStream.dat");
            Assert.IsFalse(System.IO.File.Exists(FileToCompress), "The temporary zip file '{0}' already exists.", FileToCompress);
            byte[] working = new byte[WORKING_BUFFER_SIZE];
            int n = -1;

            int sz = this.rnd.Next(21000) + 15000;
            TestContext.WriteLine("  Creating file: {0} sz({1})", FileToCompress, sz);
            CreateAndFillFileText(FileToCompress, sz);

            System.IO.FileInfo fi1 = new System.IO.FileInfo(FileToCompress);
            int crc1 = DoCrc(FileToCompress);

            // four trials, all combos of FileName and Comment null or not null.
            for (int k = 0; k < 4; k++)
            {
                string CompressedFile = String.Format("{0}-{1}.compressed", FileToCompress, k);

                using (Stream input = File.OpenRead(FileToCompress))
                {
                    using (FileStream raw = new FileStream(CompressedFile, FileMode.Create))
                    {
                        using (GZipStream compressor =
                               new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
                        {
                            // FileName is optional metadata in the GZip bytestream
                            if (k % 2 == 1)
                                compressor.FileName = FileToCompress;

                            // Comment is optional metadata in the GZip bytestream
                            if (k > 2)
                                compressor.Comment = "Compressing: " + FileToCompress;

                            byte[] buffer = new byte[1024];
                            n = -1;
                            while (n != 0)
                            {
                                if (n > 0)
                                    compressor.Write(buffer, 0, n);

                                n = input.Read(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }

                System.IO.FileInfo fi2 = new System.IO.FileInfo(CompressedFile);

                Assert.IsTrue(fi1.Length > fi2.Length, String.Format("Compressed File is not smaller, trial {0} ({1}!>{2})", k, fi1.Length, fi2.Length));


                // decompress twice:
                // once with System.IO.Compression.GZipStream and once with Ionic.Zlib.GZipStream
                for (int j = 0; j < 2; j++)
                {
                    using (var input = System.IO.File.OpenRead(CompressedFile))
                    {

                        Stream decompressor = null;
                        try
                        {
                            switch (j)
                            {
                                case 0:
                                    decompressor = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true);
                                    break;
                                case 1:
                                    decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress, true);
                                    break;
                            }

                            string DecompressedFile =
                                                        String.Format("{0}.{1}.decompressed", CompressedFile, (j == 0) ? "Ionic" : "BCL");

                            TestContext.WriteLine("........{0} ...", System.IO.Path.GetFileName(DecompressedFile));

                            using (var s2 = System.IO.File.Create(DecompressedFile))
                            {
                                n = -1;
                                while (n != 0)
                                {
                                    n = decompressor.Read(working, 0, working.Length);
                                    if (n > 0)
                                        s2.Write(working, 0, n);
                                }
                            }

                            int crc2 = DoCrc(DecompressedFile);
                            Assert.AreEqual<Int32>(crc1, crc2);

                        }
                        finally
                        {
                            if (decompressor != null)
                                decompressor.Dispose();
                        }
                    }
                }
            }
        }
Exemple #18
0
        public void MakeApiCall(CallRequestContainer reqContainer)
        {
            //Set headers
            var headers = new Dictionary<string, string> { { "Content-Type", "application/json" } };
            if (reqContainer.AuthKey == AuthType.DevSecretKey)
            {
#if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API
                headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey);
#endif
            }
            else if (reqContainer.AuthKey == AuthType.LoginSession)
            {
                headers.Add("X-Authorization", AuthKey);
            }

            headers.Add("X-ReportErrorAsSuccess", "true");
            headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString);

#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
            if (PlayFabSettings.CompressApiData)
            {
                headers.Add("Content-Encoding", "GZIP");
                headers.Add("Accept-Encoding", "GZIP");

                using (var stream = new MemoryStream())
                {
                    using (GZipStream zipstream = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression))
                    {
                        zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
                    }
                    reqContainer.Payload = stream.ToArray();
                }
            }
#endif

            //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url);
            var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, headers);

#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif

            // Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
            Action<string> wwwSuccessCallback = (response) =>
            {
                try
                {
#if PLAYFAB_REQUEST_TIMING
                    var startTime = DateTime.UtcNow;
#endif
                    var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(response, PlayFabUtil.ApiSerializerStrategy);

                    if (httpResult.code == 200)
                    {
                        // We have a good response from the server
                        reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data, PlayFabUtil.ApiSerializerStrategy);
                        reqContainer.DeserializeResultJson();
                        reqContainer.ApiResult.Request = reqContainer.ApiRequest;
                        reqContainer.ApiResult.CustomData = reqContainer.CustomData;

#if !DISABLE_PLAYFABCLIENT_API
                        ClientModels.UserSettings userSettings = null;
                        var res = reqContainer.ApiResult as ClientModels.LoginResult;
                        var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
                        if (res != null)
                        {
                            userSettings = res.SettingsForUser;
                            AuthKey = res.SessionTicket;
                        }
                        else if (regRes != null)
                        {
                            userSettings = regRes.SettingsForUser;
                            AuthKey = regRes.SessionTicket;
                        }

                        if (userSettings != null && AuthKey != null && userSettings.NeedsAttribution)
                        {
                            PlayFabIdfa.OnPlayFabLogin();
                        }

                        var cloudScriptUrl = reqContainer.ApiResult as ClientModels.GetCloudScriptUrlResult;
                        if (cloudScriptUrl != null)
                        {
                            PlayFabSettings.LogicServerUrl = cloudScriptUrl.Url;
                        }
#endif
                        try
                        {
                            PlayFabHttp.SendEvent(reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }

#if PLAYFAB_REQUEST_TIMING
                        stopwatch.Stop();
                        var timing = new PlayFabHttp.RequestTiming {
                            StartTimeUtc = startTime,
                            ApiEndpoint = reqContainer.ApiEndpoint,
                            WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds,
                            MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
                        };
                        PlayFabHttp.SendRequestTiming(timing);
#endif
                        try
                        {
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                    else
                    {
                        if (reqContainer.ErrorCallback != null)
                        {
                            reqContainer.Error = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData);
                            PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                            reqContainer.ErrorCallback(reqContainer.Error);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            };

            Action<string> wwwErrorCallback = (errorCb) =>
            {
                reqContainer.JsonResponse = errorCb;
                if (reqContainer.ErrorCallback != null)
                {
                    reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData);
                    PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                    reqContainer.ErrorCallback(reqContainer.Error);
                }
            };

            PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback));
        }
Exemple #19
0
        /// <summary>
        /// Publishes a file to Amazon S3.
        /// </summary>
        /// <param name="filePath">The path of the file to publish.</param>
        private void PublishFile(string filePath)
        {
            NameValueCollection headers = new NameValueCollection();
            string contentType = MimeType.FromCommon(filePath).ContentType;
            string objectKey = this.ObjectKey(filePath);

            if (this.OverwriteExisting || !this.ObjectExists(objectKey))
            {
                PutObjectRequest request = new PutObjectRequest()
                    .WithBucketName(this.BucketName)
                    .WithCannedACL(S3CannedACL.PublicRead)
                    .WithContentType(contentType)
                    .WithKey(objectKey)
                    .WithTimeout(this.Timeout);

                bool gzip = false;
                string tempPath = null;

                if (contentType.StartsWith("text", StringComparison.OrdinalIgnoreCase))
                {
                    gzip = true;
                    tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetRandomFileName());

                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        using (FileStream temp = File.Create(tempPath))
                        {
                            using (GZipStream gz = new GZipStream(temp, CompressionMode.Compress))
                            {
                                byte[] buffer = new byte[4096];
                                int count;

                                while (0 < (count = fs.Read(buffer, 0, buffer.Length)))
                                {
                                    gz.Write(buffer, 0, count);
                                }
                            }
                        }
                    }

                    headers["Content-Encoding"] = "gzip";
                    request = request.WithFilePath(tempPath);
                }
                else
                {
                    request = request.WithFilePath(filePath);
                }

                request.AddHeaders(headers);

                using (PutObjectResponse response = this.Client().PutObject(request))
                {
                }

                if (!String.IsNullOrEmpty(tempPath) && File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }

                this.PublisherDelegate.OnFilePublished(filePath, objectKey, gzip);
            }
            else
            {
                this.PublisherDelegate.OnFileSkipped(filePath, objectKey);
            }
        }
Exemple #20
0
        public byte[] SaveMultiplayer(Player player)
        {
            //Save world to memory
            MemoryStream bytesStream = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(bytesStream);

            //Basic world info
            SaveMultiplayer(bw);

            //Managers
            tileManager.Save(bw);
            itemManager.Save(bw);
            sectorManager.Save(bw);
            dayCycleManager.Save(bw);

            //Player avatar
            bw.Write(player.objectId);
            player.Save(bw);

            bw.Flush();

            byte[] bytes = bytesStream.ToArray();

            //Write header
            MemoryStream bytesStreamFinal = new MemoryStream();
            BinaryWriter bwFinal = new BinaryWriter(bytesStreamFinal);

            bwFinal.Write(bytes.Length);
            bwFinal.Flush();

            //Compress and write world
            GZipStream gzipStream = new GZipStream(bytesStreamFinal, CompressionMode.Compress, CompressionLevel.BestSpeed, true);
            gzipStream.Write(bytes, 0, bytes.Length);
            gzipStream.Close();

            return bytesStreamFinal.ToArray();
        }
Exemple #21
0
        /// <summary>
        /// Gzips the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static byte[] Gzip(this string input) {
            var memStream = new MemoryStream();
            using (var gzStr = new GZipStream(memStream, CompressionMode.Compress, CompressionLevel.BestCompression)) {
                gzStr.Write(input.ToByteArray(), 0, input.ToByteArray().Length);
            }

            return memStream.ToArray();
        }