static void Main(string[] args) { //压缩分为三种:1.字节数组 2.对文件的压缩 3.对字符串的压缩 //下面掩饰的是加解密字节数组 byte[] cbytes = null; //压缩 using (MemoryStream cms = new MemoryStream()) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Compress)) { //将数据写入基础流,同时会被压缩 byte[] bytes = Encoding.UTF8.GetBytes("解压缩测试"); gzip.Write(bytes, 0, bytes.Length); } cbytes = cms.ToArray(); } //解压 using (MemoryStream dms = new MemoryStream()) { using (MemoryStream cms = new MemoryStream(cbytes)) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Decompress)) { byte[] bytes = new byte[1024]; int len = 0; //读取压缩流,同时会被解压 while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { dms.Write(bytes, 0, len); } } } Console.WriteLine(Encoding.UTF8.GetString(dms.ToArray())); //result:"解压缩测试" } //———————————————————————————————————————————— //下面示例来自:http://www.cnblogs.com/yank/p/Compress.html TestGZipCompressFile(); string str = "abssssdddssssssssss11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; string orgStr = str; string result = ""; //将传入的字符串直接进行压缩,解压缩,会出现乱码。 //先转码,然后再压缩。解压缩:先解压缩,再反转码 Console.WriteLine("源字符串为:{0}", str); result = GZipCompress.Compress(str); Console.WriteLine("压缩后为:{0}", result); Console.Write("压缩前:{0},压缩后:{1}", str.Length, result.Length); Console.WriteLine("开始解压..."); Console.WriteLine("解压后:{0}", result); result = GZipCompress.Decompress(result); Console.WriteLine("解压后与源字符串对比,是否相等:{0}", result == orgStr); Console.WriteLine("源字符串为:{0}", str); result = ZipComporessor.Compress(str); Console.WriteLine("压缩后为:{0}", result); Console.Write("压缩前:{0},压缩后:{1}", str.Length, result.Length); Console.WriteLine("开始解压..."); Console.WriteLine("解压后:{0}", result); result = ZipComporessor.Decompress(result); Console.WriteLine("解压后与源字符串对比,是否相等:{0}", result == orgStr); Console.WriteLine("输入任意键,退出!"); Console.ReadKey(); }
public string Zip(string value) { //Transform string into byte[] byte[] byteArray = this.StrToByteArray(value); //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream( ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string // C# to convert a byte array to a string. byteArray = ms.ToArray(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string str = enc.GetString(byteArray); ms.Close(); sw.Dispose(); ms.Dispose(); return(str); }
public void TestMethod2() { byte[] cbytes = null; //压缩 using (MemoryStream cms = new MemoryStream()) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Compress)) { //将数据写入基础流,同时会被压缩 byte[] bytes = Encoding.UTF8.GetBytes("解压缩测试"); gzip.Write(bytes, 0, bytes.Length); } cbytes = cms.ToArray(); } //解压 using (MemoryStream dms = new MemoryStream()) { using (MemoryStream cms = new MemoryStream(cbytes)) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Decompress)) { byte[] bytes = new byte[1024]; int len = 0; //读取压缩流,同时会被解压 while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { dms.Write(bytes, 0, len); } } } Console.WriteLine(Encoding.UTF8.GetString(dms.ToArray())); } }
} // End Sub CreateHugeGzipFile private static void CreateHugeBullshitGzipFile() { if (System.IO.File.Exists(fileName)) { return; } byte[] buffer = new byte[ONE_MEGABYTE]; // 1MB using (System.IO.FileStream gzipTargetAsStream = System.IO.File.OpenWrite(fileName)) { using (System.IO.Compression.GZipStream gzipStream = new System.IO.Compression.GZipStream(gzipTargetAsStream, System.IO.Compression.CompressionLevel.Optimal)) { try { for (int i = 0; i < REPEAT_COUNT; ++i) { gzipStream.Write(buffer, 0, ONE_MEGABYTE); gzipStream.Flush(); gzipTargetAsStream.Flush(); } // Next i } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); } } // End Using GZipStream } // End Using gzipTargetAsStream } // End Sub CreateHugeBullshitGzipFile
public void CompressAFile() { string folder = @"E:\Examen de certificacion C#"; string uncompressedFilePath = Path.Combine(folder, "uncompressed.dat"); string compressedFilePath = Path.Combine(folder, "compressed.zip"); byte[] dataToCompress = Enumerable.Repeat((byte)'a', 1024 * 1024).ToArray(); using (FileStream ufs = File.Create(uncompressedFilePath)) { ufs.Write(dataToCompress, 0, dataToCompress.Length); } using (FileStream compressedFileStream = File.Create(compressedFilePath)) { using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(compressedFileStream, System.IO.Compression.CompressionMode.Compress)) { zip.Write(dataToCompress, 0, dataToCompress.Length); } } FileInfo uf = new FileInfo(uncompressedFilePath); FileInfo cf = new FileInfo(compressedFilePath); Console.WriteLine(uf.Length); Console.WriteLine(cf.Length); }
/// <summary> /// Serializes the <paramref name="instance"/> instance to the specified file. /// </summary> /// <typeparam name="T">Type of object to serialize</typeparam> /// <param name="instance">The object to serialize.</param> /// <param name="file">The file to save the object to.</param> /// <param name="compress">When true, uses GZIP compression on the json string saved to the <paramref name="file"/></param> public static void Save <T>(T instance, string file, bool compress) { if (System.IO.File.Exists(file)) { System.IO.File.Delete(file); } using (var stream = System.IO.File.OpenWrite(file)) { if (compress) { using (var sw = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress)) { var bytes = Encoding.UTF32.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(instance, Formatting.None, new JsonSerializerSettings() { TraceWriter = LogWriter, TypeNameHandling = TypeNameHandling.All })); sw.Write(bytes, 0, bytes.Length); } } else { using (var sw = new System.IO.StreamWriter(stream)) { sw.Write(JsonConvert.SerializeObject(instance, Formatting.Indented, new JsonSerializerSettings() { TraceWriter = LogWriter, TypeNameHandling = TypeNameHandling.All })); } } } }
public void WillDecodeGZipedResponse() { var testable = new TestableJavaScriptReducer(); var mockWebResponse = new Mock <WebResponse>(); var ms = new MemoryStream(); var stream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); stream.Write(new UTF8Encoding().GetBytes("my response"), 0, "my response".Length); stream.Close(); var encodedArray = ms.ToArray(); ms.Close(); stream.Dispose(); ms.Dispose(); mockWebResponse.Setup(x => x.GetResponseStream()).Returns(new MemoryStream(encodedArray)); mockWebResponse.Setup(x => x.Headers).Returns(new WebHeaderCollection() { { "Content-Encoding", "gzip" } }); testable.Mock <IWebClientWrapper>().Setup(x => x.Download <JavaScriptResource>("http://host/js1.js")).Returns(mockWebResponse.Object); testable.Mock <IMinifier>().Setup(x => x.Minify <JavaScriptResource>("my response;\r\n")).Returns("min"); var result = testable.ClassUnderTest.Process("http://host/js1.js::"); testable.Mock <IStore>().Verify( x => x.Save(Encoding.UTF8.GetBytes("min").MatchEnumerable(), result, "http://host/js1.js::"), Times.Once()); ms.Dispose(); }
public void send_world_to_client(NetIncomingMessage p, Exilania g, Display d, World w) { /*System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.HashAlgorithm.Create(); * System.IO.FileStream fs = new System.IO.FileStream(@"worlds/" + w.name + ".wld",System.IO.FileMode.Open,System.IO.FileAccess.Read); * byte[] hash = ha.ComputeHash(fs); * fs.Close(); * Exilania.text_stream.WriteLine("Hash code before resaving: "+BitConverter.ToString(hash));*/ w.write_world(); /*fs = new System.IO.FileStream(@"worlds/" + w.name + ".wld", System.IO.FileMode.Open, System.IO.FileAccess.Read); * hash = ha.ComputeHash(fs); * fs.Close(); * Exilania.text_stream.WriteLine("Hash code after resaving: " + BitConverter.ToString(hash));*/ string file_name = "world" + w.world_number.ToString(); byte[] data_write = System.IO.File.ReadAllBytes(@"worlds/" + file_name + ".wld"); System.IO.FileStream fs = new System.IO.FileStream(@"worlds/network_game.wlz", System.IO.FileMode.Create, System.IO.FileAccess.Write); using (fs) { System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress); gzip.Write(data_write, 0, (int)data_write.Length); } data_write = System.IO.File.ReadAllBytes(@"worlds/network_game.wlz"); System.IO.File.Delete(@"worlds/network_game.wlz"); NetOutgoingMessage i = udp_server.CreateMessage(); i.Write((byte)10); i.Write(file_name); i.Write(data_write.Length); i.Write(data_write); udp_server.SendMessage(i, p.SenderConnection, NetDeliveryMethod.ReliableOrdered, 6); }
// GET: Api/Post/Add3 public JsonResult Add3() { PostModel model = new PostModel(); model.PDate = DateTime.Now; string fileName = Server.MapPath("~/App_Data/test3.json"); model.PText = fileName; System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PostModel)); System.IO.MemoryStream stream1 = new System.IO.MemoryStream(); ser.WriteObject(stream1, model); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = stream1.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } return Json(model, JsonRequestBehavior.AllowGet); }
public static string CompressString(string text) { if (string.IsNullOrWhiteSpace(text)) { return(text); } byte[] rawData = Encoding.UTF8.GetBytes(text); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { using (System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream( memoryStream, System.IO.Compression.CompressionMode.Compress, true)) { gZipStream.Write(rawData, 0, rawData.Length); } memoryStream.Position = 0; byte[] compressedData = new byte[memoryStream.Length]; memoryStream.Read(compressedData, 0, compressedData.Length); byte[] gzipData = new byte[compressedData.Length + 4]; Buffer.BlockCopy(compressedData, 0, gzipData, 4, compressedData.Length); Buffer.BlockCopy(BitConverter.GetBytes(rawData.Length), 0, gzipData, 0, 4); return(Convert.ToBase64String(gzipData)); } }
public static string Zip(string text) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; System.IO.MemoryStream outStream = new System.IO.MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return(Convert.ToBase64String(gzBuffer)); }
} // End Sub Main public static void CompressFile(string FileToCompress, string CompressedFile) { //byte[] buffer = new byte[1024 * 1024 * 64]; byte[] buffer = new byte[1024 * 1024]; // 1MB using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress)) { using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile)) { using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile, System.IO.Compression.CompressionMode.Compress)) { int bytesRead = 0; while (bytesRead < sourceFile.Length) { int ReadLength = sourceFile.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, ReadLength); output.Flush(); bytesRead += ReadLength; } // Whend destinationFile.Flush(); } // End Using System.IO.Compression.GZipStream output destinationFile.Close(); } // End Using System.IO.FileStream destinationFile // Close the files. sourceFile.Close(); } // End Using System.IO.FileStream sourceFile } // End Sub CompressFile
public static string ZipCompress(this string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); return sB.ToString(); }
public static string Zip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); return(sB.ToString()); }
/// <summary> /// Компрессия или декомпрессия файла /// </summary> /// <param name="fromFile">Исходный файл для компрессии или декомпрессии</param> /// <param name="toFile">Целевой файл</param> /// <param name="compressionMode">Указывает на компрессию или декомпрессию</param> private static void CompressOrDecompressFile(string fromFile, string toFile, System.IO.Compression.CompressionMode compressionMode) { System.IO.FileStream toFs = null; System.IO.Compression.GZipStream gzStream = null; System.IO.FileStream fromFs = new System.IO.FileStream(fromFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); try { toFs = new System.IO.FileStream(toFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); gzStream = new System.IO.Compression.GZipStream(toFs, compressionMode); byte[] buf = new byte[fromFs.Length]; fromFs.Read(buf, 0, buf.Length); gzStream.Write(buf, 0, buf.Length); } finally { if (gzStream != null) gzStream.Close(); if (toFs != null) toFs.Close(); fromFs.Close(); } }
public List <int> call(double[,] data, int[] start, int[] end) { var corrId = Guid.NewGuid().ToString(); var props = channel.CreateBasicProperties(); props.ReplyTo = replyQueueName; props.CorrelationId = corrId; Dictionary <string, object> obj = new Dictionary <string, object>(); obj.Add("data", data); obj.Add("start", start); obj.Add("end", end); var json = JsonConvert.SerializeObject(obj); byte[] payload; using (MemoryStream cms = new MemoryStream()) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Compress)) { byte[] bytes = Encoding.UTF8.GetBytes(json); gzip.Write(bytes, 0, bytes.Length); } payload = cms.ToArray(); } channel.BasicPublish(exchange: "", routingKey: methodname, basicProperties: props, body: payload); while (true) { var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); if (ea.BasicProperties.CorrelationId == corrId) { using (MemoryStream dms = new MemoryStream()) { using (MemoryStream cms = new MemoryStream(ea.Body)) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Decompress)) { byte[] bytes = new byte[1024 * 64]; int len = 0; //读取压缩流,同时会被解压 while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { dms.Write(bytes, 0, len); } } } var respjson = Encoding.UTF8.GetString(dms.ToArray()); var result = JsonConvert.DeserializeObject <List <int> >(respjson); return(result); } } } }
private byte[] Zip(byte[] v) { MemoryStream result = new MemoryStream(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(result, System.IO.Compression.CompressionLevel.Optimal)) gz.Write(v, 0, v.Length); return(result.ToArray()); }
/// <summary> /// This function return a byte array compressed by GZIP algorithm. /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressGZIP(byte[] data) { System.IO.MemoryStream streamoutput = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(streamoutput, System.IO.Compression.CompressionMode.Compress, false); gzip.Write(data, 0, data.Length); gzip.Close(); return streamoutput.ToArray(); }
/// <summary> /// 保存到流中。 /// </summary> /// <param name="stream">流。</param> /// <returns>返回是否成功。</returns> public bool Save(System.IO.Stream stream) { if (stream == null || !stream.CanWrite) { return(false); } using (System.IO.Stream compresStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress, true)) { System.Collections.Generic.Dictionary <string, object> root = new System.Collections.Generic.Dictionary <string, object>(); root.Add("version", _version); System.Collections.Generic.Dictionary <string, object> items = new System.Collections.Generic.Dictionary <string, object>(); root.Add("items", items); bool has = _list != null && _list.Count > 0; if (has) { for (int i = 0; i < _list.Count; i++) { Resource item = _list[i]; items.Add(item.Name, new object[] { item.Offset, item.Length }); } } { string json = Symbol.Serialization.Json.ToString(root); byte[] buffer = BitConverter.GetBytes((ushort)json.Length); compresStream.Write(buffer, 0, buffer.Length); buffer = System.Text.Encoding.UTF8.GetBytes(json); compresStream.Write(buffer, 0, buffer.Length); } if (has) { for (int i = 0; i < _list.Count; i++) { Resource item = _list[i]; compresStream.Write(item.Data, 0, item.Length); } } compresStream.Flush(); stream.Flush(); } return(true); }
/// <summary> /// 分析网络数据包并进行转换为信息对象 /// </summary> /// <param name="packs">接收到的封包对象</param> /// <returns></returns> /// <remarks> /// 对于分包消息,如果收到的只是片段并且尚未接收完全,则不会进行解析 /// </remarks> public static IPMessager.Entity.Message ParseToMessage(params Entity.PackedNetworkMessage[] packs) { if (packs.Length == 0 || (packs[0].PackageCount > 1 && packs.Length != packs[0].PackageCount)) { return(null); } //尝试解压缩,先排序 Array.Sort(packs); //尝试解压缩 System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); try { Array.ForEach(packs, s => zip.Write(s.Data, 0, s.Data.Length)); } catch (Exception) { OnDecompressFailed(new DecomprssFailedEventArgs(packs)); return(null); } zip.Close(); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); //构造读取流 System.IO.BinaryReader br = new System.IO.BinaryReader(ms, System.Text.Encoding.Unicode); //开始读出数据 IPMessager.Entity.Message m = new FSLib.IPMessager.Entity.Message(packs[0].RemoteIP); m.PackageNo = br.ReadUInt64(); //包编号 ulong tl = br.ReadUInt64(); m.Command = (Define.Consts.Commands)(tl & 0xFF); //命令编码 m.Options = tl & 0xFFFFFF00; //命令参数 m.UserName = br.ReadString(); //用户名 m.HostName = br.ReadString(); //主机名 int length = br.ReadInt32(); m.NormalMsgBytes = new byte[length]; br.Read(m.NormalMsgBytes, 0, length); length = br.ReadInt32(); m.ExtendMessageBytes = new byte[length]; br.Read(m.ExtendMessageBytes, 0, length); if (!Consts.Check(m.Options, Consts.Cmd_All_Option.BinaryMessage)) { m.NormalMsg = System.Text.Encoding.Unicode.GetString(m.NormalMsgBytes, 0, length); //正文 m.ExtendMessage = System.Text.Encoding.Unicode.GetString(m.ExtendMessageBytes, 0, length); //扩展消息 } return(m); }
public override void Serialize(Stream stream, object obj) { var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj); var data = this.Encoding.GetBytes(json); using (var gzip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionLevel.Fastest)) { gzip.Write(data, 0, data.Length); } }
/// <summary> /// 压缩 /// </summary> /// <param name="value">值</param> public static byte[] Compress(byte[] value) { var ms = new MicrosoftSystem.IO.MemoryStream(); var cs = new MicrosoftSystem.IO.Compression.GZipStream(ms, MicrosoftSystem.IO.Compression.CompressionMode.Compress, true); cs.Write(value, 0, value.Length); cs.Close(); return(ms.ToArray()); }
//based in a code of Dario Solera: http://www.codeproject.com/aspnet/ViewStateCompression.asp public byte[] GZipCompress(byte[] data) { MemoryStream output = new MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress, true); gzip.Write(data, 0, data.Length); gzip.Close(); return(output.ToArray()); }
//zip压缩字节 //1.创建压缩的数据流 //2.设定compressStream为存放被压缩的文件流,并设定为压缩模式 //3.将需要压缩的字节写到被压缩的文件流 public static byte[] CompressBytes(byte[] bytes) { using (MemoryStream compressStream = new MemoryStream()) { using (var zipStream = new System.IO.Compression.GZipStream(compressStream, System.IO.Compression.CompressionMode.Compress)) zipStream.Write(bytes, 0, bytes.Length); return(compressStream.ToArray()); } }
public static byte[] zipBase64(byte[] rawData) { MemoryStream ms = new MemoryStream(); System.IO.Compression.GZipStream compressedzipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); compressedzipStream.Write(rawData, 0, rawData.Length); compressedzipStream.Close(); return(ms.ToArray()); }
} // End Sub ServerThread private static byte[] Compress(byte[] data) { using (System.IO.MemoryStream compressedStream = new System.IO.MemoryStream()) using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return(compressedStream.ToArray()); } }
public override void Serialize(Stream stream, object obj) { var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(obj); var data = this.Encoding.GetBytes(json); using (var gzip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionLevel.Fastest)) { gzip.Write(data, 0, data.Length); } }
public byte[] EncodeGzip(byte[] gzipData) { using (MemoryStream ms = new MemoryStream()) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { gzip.Write(gzipData, 0, gzipData.Length); } return(ms.ToArray()); } }
public static byte[] Compress(byte[] InputBytes) { using (var outputStream = new System.IO.MemoryStream()) { using (var gZipStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionLevel.Optimal)) { gZipStream.Write(InputBytes, 0, InputBytes.Length); } return(outputStream.ToArray()); } }
static void ZipFile(string file) { var target = file + ".gz"; using (var ts = System.IO.File.OpenWrite(target)) using (var gz = new System.IO.Compression.GZipStream(ts, System.IO.Compression.CompressionMode.Compress)) { var buffer = System.IO.File.ReadAllBytes(file); gz.Write(buffer, 0, buffer.Length); } }
/// <summary> /// Gzips a string /// </summary> public static byte[] ConvertGzip(string message, System.Text.Encoding encoding) { byte[] data = encoding.GetBytes(message); using (var compressedStream = new System.IO.MemoryStream()) using (var zipStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return(compressedStream.ToArray()); } }
public byte[] Compress(string key) { var KeyByteArray = Encoding.UTF8.GetBytes(key); var OutputStream = new MemoryStream(); using (var Gzip = new System.IO.Compression.GZipStream(OutputStream, System.IO.Compression.CompressionMode.Compress)) { Gzip.Write(KeyByteArray, 0, KeyByteArray.Length); } return(OutputStream.ToArray()); }
/// <summary> /// 压缩指定文件 /// </summary> public static byte[] CompressBuffer(byte[] data) { using (var ms = new System.IO.MemoryStream()) using (var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { zs.Write(data, 0, data.Length); zs.Close(); ms.Close(); return(ms.ToArray()); } }
/// <summary> /// GZip压缩 /// 核心方法 /// </summary> /// <param name="toZipByteArr">待压缩的byte[]</param> /// <returns>压缩后的byte[]</returns> public static byte[] Compress(byte[] toZipByteArr) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.IO.Compression.GZipStream compressedzipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { compressedzipStream.Write(toZipByteArr, 0, toZipByteArr.Length); compressedzipStream.Close(); return(ms.ToArray()); } } }
private byte[] Compress(string data) { using (System.IO.MemoryStream mem = new System.IO.MemoryStream()) { using (System.IO.Compression.GZipStream g = new System.IO.Compression.GZipStream(mem, System.IO.Compression.CompressionLevel.Optimal)) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data); g.Write(bytes, 0, bytes.Length); } return mem.ToArray(); } }
public static byte[] GZip(byte[] byteArray) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string return(ms.ToArray()); } }
static public byte[] CompressGzip(byte[] original) { using (var compressedStream = new System.IO.MemoryStream()) { using (var compressStream = new System.IO.Compression.GZipStream( compressedStream, System.IO.Compression.CompressionMode.Compress)) { compressStream.Write(original); compressStream.Flush(); return(compressedStream.ToArray()); } } }
private void start() { //Debug.Assert(MAPSIZE == 64, "The BlockBulkTransfer message requires a map size of 64."); for (byte x = 0; x < MAPSIZE; x++) for (byte y = 0; y < MAPSIZE; y += 16) { NetBuffer msgBuffer = infsN.CreateBuffer(); msgBuffer.Write((byte)Infiniminer.InfiniminerMessage.BlockBulkTransfer); if (!compression) { msgBuffer.Write(x); msgBuffer.Write(y); for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < MAPSIZE; z++) msgBuffer.Write((byte)(infs.blockList[x, y + dy, z])); if (client.Status == NetConnectionStatus.Connected) infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered); } else { //Compress the data so we don't use as much bandwith - Xeio's work var compressedstream = new System.IO.MemoryStream(); var uncompressed = new System.IO.MemoryStream(); var compresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Compress); //Send a byte indicating that yes, this is compressed msgBuffer.Write((byte)255); //Write everything we want to compress to the uncompressed stream uncompressed.WriteByte(x); uncompressed.WriteByte(y); for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < MAPSIZE; z++) uncompressed.WriteByte((byte)(infs.blockList[x, y + dy, z])); //Compress the input compresser.Write(uncompressed.ToArray(), 0, (int)uncompressed.Length); //infs.ConsoleWrite("Sending compressed map block, before: " + uncompressed.Length + ", after: " + compressedstream.Length); compresser.Close(); //Send the compressed data msgBuffer.Write(compressedstream.ToArray()); if (client.Status == NetConnectionStatus.Connected) infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered); } } conn.Abort(); }
public byte[] compress(byte[] data) { MemoryStream packed = new MemoryStream(); System.IO.Stream packer = new System.IO.Compression.GZipStream( packed, System.IO.Compression.CompressionMode.Compress ); packer.Write(data, 0, data.Length); packer.Close(); return packed.ToArray(); }
public static string lerror = ""; // Gets the last error that occurred in this struct. Similar to the C perror(). #endregion Fields #region Methods public static bool compress(string infile, string outfile) { try { byte[] ifdata = System.IO.File.ReadAllBytes(infile); System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(sw.BaseStream, System.IO.Compression.CompressionMode.Compress); gzs.Write(ifdata, 0, ifdata.Length); gzs.Close(); gzs.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return false; } return true; }
/// <summary> /// Compress contents to gzip /// </summary> /// <param name="s"></param> /// <returns></returns> /// <remarks></remarks> public static byte[] GZIP(ref string s) { byte[] buffer = null; byte[] compressedData = null; MemoryStream oMemoryStream = null; System.IO.Compression.GZipStream compressedzipStream = null; oMemoryStream = new MemoryStream(); buffer = System.Text.Encoding.UTF8.GetBytes(s); compressedzipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); compressedzipStream.Dispose(); compressedzipStream.Close(); compressedData = oMemoryStream.ToArray(); oMemoryStream.Close(); return compressedData; }
/// <summary> /// In Memory Compression with Gzip /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GZip_Compress(this byte[] data) { byte[] res = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; using (ms = new MemoryStream()) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, false)) { gz.Write(data, 0, data.Length); } res = ms.ToArray(); } return res; }
/// <summary> /// �������л���ѹ�� /// </summary> /// <param name="ds"></param> /// <returns></returns> public static byte[] Compress(object obj, Type type) { byte[] compressedBuf; CompressionSerialize compressionSerialize = new CompressionSerialize(); #region serialize byte[] buf = compressionSerialize.Serialize(obj, type); #endregion System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); gs.Write(buf, 0, buf.Length); gs.Close(); compressedBuf = ms.ToArray(); return compressedBuf; }
/// <summary> /// DataSet���л���ѹ�� /// </summary> /// <param name="ds"></param> /// <returns></returns> public static byte[] CompressDataSet(DataSet ds) { byte[] compressedBuf; #region serialize RawSerializer rs = new RawSerializer(); byte[] buf = rs.Serialize(ds); #endregion System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); gs.Write(buf, 0, buf.Length); gs.Close(); compressedBuf = ms.ToArray(); return compressedBuf; }
// <summary> /// 对byte数组进行压缩 /// </summary> /// <param name="data">待压缩的byte数组</param> /// <returns>压缩后的byte数组</returns> public static byte[] Compress(byte[] data) { try { MemoryStream ms = new MemoryStream(); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.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 (Exception e) { throw new Exception(e.Message); } }
public string Zip(string text) { byte[] buffer = System.Text.Encoding.Unicode.GetBytes(text); MemoryStream ms = new MemoryStream(); using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; MemoryStream outStream = new MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return Convert.ToBase64String(gzBuffer); }
public static string Zip(string s) { //Transform string into byte[] byte[] byteArray = new byte[s.Length]; int indexBA = 0; foreach (char item in s.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) using (System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); ms.Close(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } //// check if we didn't gain anything //if (sB.Length <= s.Length) //{ // return s; //} return sB.ToString(); } }
/// <summary> /// In Memory Compression with Gzip /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressGZip(this byte[] data) { byte[] res = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; try { using (ms = new MemoryStream()) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, false)) { gz.Write(data, 0, data.Length); gz.Close(); } res = ms.ToArray(); } } catch { res = null; } finally { if (gz != null) { gz.Close(); gz.Dispose(); } if (ms != null) { ms.Close(); ms.Dispose(); } } return res; }
static void Main(string[] args) { System.IO.Stream packer = new System.IO.Compression.GZipStream( System.Console.OpenStandardOutput(), System.IO.Compression.CompressionMode.Compress ); MemoryStream buf = new MemoryStream(); System.IO.Stream stdin = System.Console.OpenStandardInput(); byte[] chunk = new byte[10240]; int n = stdin.Read(chunk, 0, chunk.Length); while (n > 0) { buf.Write(chunk, 0, n); n = stdin.Read(chunk, 0, chunk.Length); } packer.Write(buf.GetBuffer(), 0, (int)buf.Length); packer.Close(); }
public void accept(string txtName) { textName = txtName; string type = Request.ContentType; int separator = type.IndexOf("/"); string compressionFormat = type.Substring(separator+1); int len = txtName.Length; //compress byte[] stringToByte=new byte[len+1]; int byteIndex=0; foreach(char c in txtName.ToCharArray()) { stringToByte[byteIndex++] = (byte)c; } var bytes = Encoding.ASCII.GetBytes(txtName); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzipStream = new System.IO.Compression.GZipStream(memoryStream,System.IO.Compression.CompressionMode.Compress); gzipStream.Write(bytes,0,bytes.Length); gzipStream.Close(); stringToByte = memoryStream.ToArray(); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(stringToByte.Length); foreach(byte b in stringToByte) { stringBuilder.Append((char)b); } memoryStream.Close(); gzipStream.Dispose(); memoryStream.Dispose(); string s = stringBuilder.ToString(); //Decompress byte[] decompressStream=new byte[s.Length]; byteIndex=0; foreach(char c in s.ToCharArray()) { decompressStream[byteIndex++]=(byte)c; } System.IO.MemoryStream ms = new System.IO.MemoryStream(decompressStream); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms,System.IO.Compression.CompressionMode.Decompress); int byteRead = gs.Read(decompressStream,0,decompressStream.Length); System.Text.StringBuilder builder = new System.Text.StringBuilder(byteRead); foreach(byte b in decompressStream) { builder.Append((char)b); } ms.Close(); gs.Close(); ms.Dispose(); gs.Dispose(); String str = builder.ToString(); int a = 0; }
public override void EmitCreation(CodeGen cg) { if (cg.IsDynamicMethod) { throw new NotSupportedException("no can do"); } else { var tg = cg.TypeGen; var ag = tg.AssemblyGen; index = tg.ConstantCounter; var snippets = ScriptDomainManager.CurrentManager.Snippets; if (snippets.Assembly == ag || snippets.DebugAssembly == ag) { var sym = Runtime.Builtins.GenSym("s11n:" + index); Runtime.Builtins.SetSymbolValueFast(sym, value); cg.EmitSymbolId((SymbolId) sym); cg.EmitCall(typeof(Runtime.Builtins), "SymbolValue"); } else { fs = tg.AddStaticField(typeof(object), "s11n:" + index) as StaticFieldSlot; tg.SerializedConstants.Add(this); var tcg = tg.TypeInitializer; if (index == 0) { arrloc = tcg.DeclareLocal(typeof(object[])); // first // setup deserializtion to array, then assign to fields tcg.EmitType(tg.TypeBuilder); tcg.EmitCall(typeof(Runtime.Helpers), "DeserializeAssemblyConstants"); tcg.Emit(OpCodes.Stloc, arrloc); tg.CreatingType += (sender, ea) => { var constants = new List<object>(); foreach (SerializedConstant sc in tg.SerializedConstants) { constants.Add(sc.value); } var constantsarray = constants.ToArray(); MemoryStream s = new MemoryStream(); bf.Serialize(s, constantsarray); s.Position = 0; totallength += s.Length; var mb = tg.TypeBuilder.Module as ModuleBuilder; if (compress) { var cms = new MemoryStream(); var cs = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Compress, true); var content = s.ToArray(); cs.Write(content, 0, content.Length); cs.Close(); mb.DefineManifestResource("SerializedConstants.gz", cms, System.Reflection.ResourceAttributes.Public); } else { mb.DefineManifestResource("SerializedConstants", s, System.Reflection.ResourceAttributes.Public); } }; } tcg.Emit(OpCodes.Ldloc, ((SerializedConstant) tg.SerializedConstants[0]).arrloc); tcg.EmitInt(index); tcg.Emit(OpCodes.Ldelem_Ref); fs.EmitSet(tcg); fs.EmitGet(cg); } tg.ConstantCounter++; } }
public void Handler(WebServiceHandler h) { // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201301/20130103 if (h.Context.Request.Path == "/view-source") { var Response = h.Context.Response; Console.WriteLine(); h.Context.Request.Headers.AllKeys.WithEach( Header => { Console.WriteLine(Header + ": " + h.Context.Request.Headers[Header]); } ); // http://code.google.com/p/googleappengine/issues/detail?id=1804 // http://stackoverflow.com/questions/9772061/app-engine-accept-encoding // https://developers.google.com/appengine/docs/python/runtime#Responses var AcceptEncoding = h.Context.Request.Headers["Accept-Encoding"]; // http://stackoverflow.com/questions/6891034/sending-a-pre-gzipped-javascript-to-the-web-browser // appengine does not allow this for now. //Accept-Encoding:gzip,deflate,sdch if (!string.IsNullOrEmpty(AcceptEncoding)) if (AcceptEncoding.Contains("gzip")) { // http://www.dotnetperls.com/gzip-aspnet //Response.ContentType = "text/javascript"; Response.ContentType = "application/x-gzip"; var app = h.Applications[0]; Response.AddHeader("Content-Encoding", "gzip"); Response.AddHeader("X-GZipAssemblyFile", app.GZipAssemblyFile); #if !flag1 Response.WriteFile("/" + app.GZipAssemblyFile); #else var m = new MemoryStream(); var mgz = new System.IO.Compression.GZipStream(m, System.IO.Compression.CompressionMode.Compress); new StreamWriter(mgz) { AutoFlush = true }.WriteLine("\n/* gzip start */\n"); var size = 0; app.References.WithEach( f => { var Name = f.AssemblyFile; var bytes = File.ReadAllBytes(Name + ".js"); size += bytes.Length; Response.AddHeader("X-Assembly", "" + new { Name, bytes.Length }); mgz.Write(bytes, 0, bytes.Length); } ); new StreamWriter(mgz) { AutoFlush = true }.WriteLine("\n/* gzip end */\n"); //mgz.Flush(); // http://code.google.com/p/tar-cs/issues/detail?id=14 mgz.Close(); //Response.AddHeader("Content-Length", "" + m.Length); // Cannot access a closed Stream. //m.Position = 0; // var gzbytes = m.ToArray(); Response.AddHeader("X-GZip-Ratio", "" + (int)(gzbytes.Length * 100 / size) + "% of " + size + " bytes"); File.WriteAllBytes(app.References.Last().AssemblyFile + ".js.gz", gzbytes); Response.OutputStream.Write(gzbytes, 0, gzbytes.Length); #endif h.CompleteRequest(); } } }
private void Compress() { if (this._UnCompressed.Length == 0) { this._Compressed = string.Empty; return; } string Result = string.Empty; try { //Convert the uncompressed string into a byte array byte[] UnZippedData = this._TextEncoding.GetBytes(this._UnCompressed); //Compress the byte array System.IO.MemoryStream MS = new System.IO.MemoryStream(); System.IO.Compression.GZipStream GZip = new System.IO.Compression.GZipStream(MS, System.IO.Compression.CompressionMode.Compress); GZip.Write(UnZippedData, 0, UnZippedData.Length); //Don't FLUSH here - it possibly leads to data loss! GZip.Close(); byte[] ZippedData = null; //Encrypt the compressed byte array, if required if (this._Passphrase.Length > 0) { ZippedData = Encrypt(MS.ToArray()); } else { ZippedData = MS.ToArray(); } //Convert the compressed byte array back to a string Result = System.Convert.ToBase64String(ZippedData); MS.Close(); GZip.Dispose(); MS.Dispose(); } catch (Exception) { //Keep quiet - in case of an exception an empty string is returned } finally { this._Compressed = Result; } }
static void ZipFile(string file) { var target = file + ".gz"; using (var ts = System.IO.File.OpenWrite(target)) using (var gz = new System.IO.Compression.GZipStream(ts, System.IO.Compression.CompressionMode.Compress)) { var buffer = System.IO.File.ReadAllBytes(file); gz.Write(buffer, 0, buffer.Length); } }
//public static Type GetTypeFromXML(string xml) //{ // string typename; // int ilt = xml.IndexOf(">"); // int ispace = xml.IndexOf(" "); // if (ispace == -1) ispace = int.MaxValue; // if (ispace > ilt) // { // typename = xml.Substring(1, ilt - 1); // } // else // { // typename = xml.Substring(1, ispace - 1); // } // return (Type)Current.GlobalTypes[typename]; //} public static byte[] GZipMemory(byte[] Buffer) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream GZip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); GZip.Write(Buffer, 0, Buffer.Length); GZip.Close(); byte[] Result = ms.ToArray(); ms.Close(); return Result; }
/// <summary> /// 压缩指定文件 /// </summary> /// <param name="path"></param> /// <param name="destFile"></param> public void CompressFile(string path, string destFile) { using (var ms = new System.IO.MemoryStream()) using (var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { var buffer = System.IO.File.ReadAllBytes(path); zs.Write(buffer, 0, buffer.Length); zs.Close(); ms.Close(); System.IO.File.WriteAllBytes(destFile, ms.ToArray()); } }
internal void threadproc() { const int MAX_SIZE_PER_RECEIVE = 0x400 * 64; byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE]; for (; ; ) { dfs.DfsFile.FileNode node; int partnum; lock (this) { if (nextpart >= parts.Count) { break; } partnum = nextpart; node = parts[nextpart++]; } string localfullname = localstartname + partnum.ToString() + localendname; using (System.IO.FileStream _fs = new System.IO.FileStream(localfullname, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fs = _fs; //if (localendname.EndsWith(".gz")) { fs = new System.IO.Compression.GZipStream(_fs, System.IO.Compression.CompressionMode.Compress); } //string netpath = NetworkPathForHost(node.Host.Split(';')[0]) + @"\" + node.Name; using (System.IO.Stream _fc = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fc = _fc; if (1 == dc.slave.CompressDfsChunks) { fc = new System.IO.Compression.GZipStream(_fc, System.IO.Compression.CompressionMode.Decompress); } { int xread = StreamReadLoop(fc, fbuf, 4); if (4 == xread) { int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf); StreamReadExact(fc, fbuf, hlen - 4); } } for (; ; ) { int xread = fc.Read(fbuf, 0, MAX_SIZE_PER_RECEIVE); if (xread <= 0) { break; } fs.Write(fbuf, 0, xread); } fc.Close(); } fs.Close(); try { System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity(); fsec.AddAccessRule(rule); System.IO.File.SetAccessControl(localfullname, fsec); } catch(Exception e) { Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername); Console.Error.WriteLine(e.ToString()); } } //if (verbose) { Console.Write('*'); ConsoleFlush(); } } }
private void SaveWebPost(string fileName, PostModel model) { WebPostModel wPost = new WebPostModel() { PTitle = model.PTitle, PText = model.PText, PLink = model.PLink, PImage = model.PImage, PDate = model.PDate.ToString("yyyy-MM-ddTHH:mm:ss"), PPrice = model.PPrice }; System.IO.MemoryStream msPost = new System.IO.MemoryStream(); System.Runtime.Serialization.Json.DataContractJsonSerializer dcJsonPost = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(WebPostModel)); dcJsonPost.WriteObject(msPost, wPost); using (System.IO.FileStream f2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create)) { byte[] jsonArray = msPost.ToArray(); using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(f2, System.IO.Compression.CompressionMode.Compress)) { gz.Write(jsonArray, 0, jsonArray.Length); } } }
/// <summary> /// Compress contents to gzip /// </summary> /// <param name="input"></param> /// <returns></returns> /// <remarks></remarks> public static byte[] GZIP(ref byte[] input) { try { byte[] compressedData = null; MemoryStream oMemoryStream = null; System.IO.Compression.GZipStream compressedzipStream = null; oMemoryStream = new MemoryStream(); compressedzipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Compress, false); compressedzipStream.Write(input, 0, input.Length); compressedzipStream.Close(); compressedData = oMemoryStream.ToArray(); compressedzipStream.Dispose(); compressedzipStream.Close(); oMemoryStream.Close(); return compressedData; } catch (Exception ex) { return null; } }
// 変換の実体 bool generate(string inputTeXFilePath, string outputFilePath) { abort = false; outputFileNames = new List<string>(); string extension = Path.GetExtension(outputFilePath).ToLower(); string tmpFileBaseName = Path.GetFileNameWithoutExtension(inputTeXFilePath); string inputextension = Path.GetExtension(inputTeXFilePath).ToLower(); // とりあえずPDFを作る int generated; if (inputextension == ".tex") { if (!tex2dvi(tmpFileBaseName + ".tex")) return false; generated = IsGenerated(Path.Combine(workingDir, tmpFileBaseName + ".pdf"), Path.Combine(workingDir, tmpFileBaseName + ".dvi")); if (generated == 0) { if (controller_ != null) controller_.showGenerateError(); return false; } if (generated == -1) { if (!dvi2pdf(tmpFileBaseName + ".dvi")) return false; } } generated = IsGenerated(Path.Combine(workingDir, tmpFileBaseName + ".pdf"), Path.Combine(workingDir, tmpFileBaseName + ".ps")); if (inputextension == ".ps" || inputextension == ".eps") { if (!ps2pdf(tmpFileBaseName + inputextension, tmpFileBaseName + ".pdf")) return false; } else if (generated == -1) { if (!ps2pdf(tmpFileBaseName + ".ps", tmpFileBaseName + ".pdf")) return false; } // ページ数を取得 int page, version; if (!pdfinfo(Path.Combine(workingDir, tmpFileBaseName + ".pdf"), out page, out version)) { controller_.showError(Properties.Resources.FAIL_PDFPAGES); return false; } // boundingBoxを取得 var bbs = new List<BoundingBoxPair>(); if (Properties.Settings.Default.keepPageSize) { bbs = readPDFBox(tmpFileBaseName + ".pdf", new List<int>(Enumerable.Range(1, page)), Properties.Settings.Default.pagebox); } else { bbs = readPDFBB(tmpFileBaseName + ".pdf", 1, page); } if (bbs == null) { if (!abort) controller_.showError(Properties.Resources.FAIL_GETBOUNDINGBOX); return false; } // 空白ページの検出 var emptyPages = new List<int>(); for (int i = 1; i <= page; ++i) { if (bbs[i - 1].bb.IsEmpty) { if (Properties.Settings.Default.leftMargin + Properties.Settings.Default.rightMargin == 0 || Properties.Settings.Default.topMargin + Properties.Settings.Default.bottomMargin == 0) { warnngs.Add(String.Format(Properties.Resources.SKIPPED_BACAUSE_EMPTY, i)); emptyPages.Add(i); } else { warnngs.Add(String.Format(Properties.Resources.EMPTYMSG, i)); } } } if (emptyPages.Count == page) { controller_.appendOutput(Properties.Resources.ALLPAGE_EMPTYMSG); return false; } var pagelist = Enumerable.Range(1, page).Where(i => !emptyPages.Contains(i)).ToList(); int gsresolution; if (Properties.Settings.Default.useLowResolution) gsresolution = 72 * Properties.Settings.Default.resolutionScale; else gsresolution = 20016; Func<bool, bool,bool> modify_pdf = (bool paint, bool resize) => { var tmppdf = TempFilesDeleter.GetTempFileName(".pdf", workingDir); tempFilesDeleter.AddFile(tmppdf); if (!pdfcrop(tmpFileBaseName + ".pdf", tmppdf, vectorExtensions.Contains(extension) || Properties.Settings.Default.yohakuUnitBP, Enumerable.Range(1, page).ToList(), bbs, paint, false, resize, version)) return false; tmpFileBaseName = Path.GetFileNameWithoutExtension(tmppdf); return true; }; // サイズ調整もする Func<bool,bool> make_pdf_without_text = (bool paint) => { if (IsNewGhostscript()) { if (!modify_pdf(paint, true)) return false; // 新しい場合はpdfwrite var tmppdf = TempFilesDeleter.GetTempFileName(".pdf", workingDir); tempFilesDeleter.AddFile(tmppdf); if (!pdf2pdf(tmpFileBaseName + ".pdf", tmppdf, gsresolution, version)) return false; tmpFileBaseName = Path.GetFileNameWithoutExtension(tmppdf); } else { if (!modify_pdf(paint, false)) return false; // 古いときはeps経由 for (int i = 1; i <= page; ++i) { if (emptyPages.Contains(i)) { make_dummyeps(tmpFileBaseName + "-" + i + ".eps"); } else { if (!pdf2eps(tmpFileBaseName + ".pdf", tmpFileBaseName + "-" + i + ".eps", gsresolution, i, version, bbs[i - 1])) return false; } } if (!eps2pdf(Enumerable.Range(1, page).Select(d => tmpFileBaseName + "-" + d + ".eps").ToList(), tmpFileBaseName + ".pdf", gsresolution, version)) return false; } return true; }; var generate_actions = new Dictionary<string, Func<bool>>(); generate_actions[".pdf"] = () => { if (Properties.Settings.Default.outlinedText) { if (!make_pdf_without_text(!Properties.Settings.Default.transparentPngFlag)) return false; } else if (!modify_pdf(!Properties.Settings.Default.transparentPngFlag, true)) return false; if (!Properties.Settings.Default.mergeOutputFiles) { foreach (var i in pagelist) { if (!pdf2pdf_pdfium(tmpFileBaseName + ".pdf", tmpFileBaseName + "-" + i.ToString() + ".pdf", i)) return false; } } else { if (!pdf2pdf_pdfium(tmpFileBaseName + ".pdf", tmpFileBaseName + "-1.pdf", pagelist)) return false; page = 1; } return true; }; generate_actions[".eps"] = () => { if (!Properties.Settings.Default.transparentPngFlag) { var tmppdf = TempFilesDeleter.GetTempFileName(".pdf", workingDir); tempFilesDeleter.AddFile(tmppdf); // ここではサイズ調整をしない if (!pdfcrop(tmpFileBaseName + ".pdf", tmppdf, true, Enumerable.Range(1, page).ToList(), bbs, true, false, false)) return false; tmpFileBaseName = Path.GetFileNameWithoutExtension(tmppdf); } foreach (var i in pagelist) { if (!pdf2eps(tmpFileBaseName + ".pdf", tmpFileBaseName + "-" + i + ".eps", gsresolution, i, version, bbs[i - 1])) return false; enlargeBB(tmpFileBaseName + "-" + i + ".eps"); } return true; }; // extensionは内部で使わない generate_actions[".svg"] = () => { if (Properties.Settings.Default.outlinedText || (Properties.Settings.Default.mergeOutputFiles && page > 1)) { if (!make_pdf_without_text(!Properties.Settings.Default.transparentPngFlag)) return false; } else if (!modify_pdf(!Properties.Settings.Default.transparentPngFlag, true)) return false; if (!pdf2img_mudraw(tmpFileBaseName + ".pdf", tmpFileBaseName + "-%d.svg", pagelist)) return false; if (Properties.Settings.Default.deleteDisplaySize) { foreach(var i in pagelist) { DeleteHeightAndWidthFromSVGFile(tmpFileBaseName + "-" + i.ToString() + ".svg"); } } if (Properties.Settings.Default.mergeOutputFiles && page > 1) { var temp = TempFilesDeleter.GetTempFileName(".svg", workingDir); var temp1 = Path.GetFileNameWithoutExtension(temp) + "-1.svg"; tempFilesDeleter.AddFile(temp1); if(svgconcat(pagelist.Select(d=>tmpFileBaseName + "-" + d.ToString() + ".svg").ToList(), temp1, Properties.Settings.Default.animationDelay, Properties.Settings.Default.animationLoop)) { page = 1; tmpFileBaseName = Path.GetFileNameWithoutExtension(temp); } else warnngs.Add(Properties.Resources.FAIL_CONCAT_IMAGES); } return true; }; generate_actions[".svgz"] = () => { if (!generate_actions[".svg"]()) return false; for(int i = 1; i <= page; ++i) { if(File.Exists(Path.Combine(workingDir,tmpFileBaseName + "-" + i.ToString() + ".svg"))) { tempFilesDeleter.AddFile(tmpFileBaseName + "-" + i.ToString() + ".svgz"); using (var ins = new FileStream(Path.Combine(workingDir, tmpFileBaseName + "-" + i.ToString() + ".svg"), FileMode.Open)) using (var outs = new FileStream(Path.Combine(workingDir, tmpFileBaseName + "-" + i.ToString() + ".svgz"), FileMode.Create)) using (var gzip = new System.IO.Compression.GZipStream(outs, System.IO.Compression.CompressionMode.Compress)) { var bytes = new byte[ins.Length]; ins.Read(bytes, 0, (int)ins.Length); gzip.Write(bytes, 0, (int)ins.Length); } } } return true; }; generate_actions[".emf"] = () => { if (Properties.Settings.Default.outlinedText) { if (!make_pdf_without_text(false)) return false; }else if (!modify_pdf(false, true)) return false; if (!dashtoline(tmpFileBaseName + ".pdf", version)) return false; if (!pdf2img_pdfium(tmpFileBaseName + ".pdf", tmpFileBaseName + "-%d" + extension, pagelist)) return false; return true; }; generate_actions[".wmf"] = generate_actions[".emf"]; Func<string, bool> generate_bitmap = (ext) => { if (!modify_pdf(!Properties.Settings.Default.transparentPngFlag, true)) return false; foreach (var i in pagelist) { if (!pdf2img(tmpFileBaseName + ".pdf", tmpFileBaseName + "-" + i + ext, i)) return false; } return true; }; generate_actions[".png"] = () => generate_bitmap(".png"); generate_actions[".jpg"] = () => generate_bitmap(".jpg"); generate_actions[".bmp"] = () => generate_bitmap(".bmp"); generate_actions[".tiff"] = () => { if (!generate_bitmap(".png")) return false; foreach (var i in pagelist) { if (!img2img_pdfium(tmpFileBaseName + "-" + i + ".png", tmpFileBaseName + "-" + i + extension)) return false; } if (Properties.Settings.Default.mergeOutputFiles && page > 1) { var temp = TempFilesDeleter.GetTempFileName(".tiff", workingDir); var temp1 = Path.GetFileNameWithoutExtension(temp) + "-1.tiff"; if(tiffconcat(pagelist.Select(d => tmpFileBaseName + "-" + d.ToString() + ".tiff").ToList(), temp1)){ page = 1; tmpFileBaseName = Path.GetFileNameWithoutExtension(temp); } else warnngs.Add(Properties.Resources.FAIL_CONCAT_IMAGES); } return true; }; generate_actions[".gif"] = () => { if (Properties.Settings.Default.transparentPngFlag) { if (!modify_pdf(false, true)) return false; if (!pdf2img_pdfium(tmpFileBaseName + ".pdf", tmpFileBaseName + "-%d" + extension, pagelist)) return false; } else { if (!generate_bitmap(".png")) return false; foreach (var i in pagelist) { if (!img2img_pdfium(tmpFileBaseName + "-" + i + ".png", tmpFileBaseName + "-" + i + extension)) return false; } } if (Properties.Settings.Default.mergeOutputFiles && page > 1) { var temp = TempFilesDeleter.GetTempFileName(".gif", workingDir); var temp1 = Path.GetFileNameWithoutExtension(temp) + "-1.gif"; if (gifconcat(pagelist.Select(d => tmpFileBaseName + "-" + d.ToString() + ".gif").ToList(), temp1, Properties.Settings.Default.animationDelay, Properties.Settings.Default.animationLoop)) { page = 1; tmpFileBaseName = Path.GetFileNameWithoutExtension(temp); } else warnngs.Add(Properties.Resources.FAIL_CONCAT_IMAGES); } return true; }; try { if (!generate_actions[extension]()) return false; } // 適当.後で考える. catch(Exception e) { warnngs.Add(e.Message); } string outputDirectory = Path.GetDirectoryName(outputFilePath); if (outputDirectory != "" && !Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } // 出力ファイルをターゲットディレクトリにコピー if (page == 1) { string generatedFile = Path.Combine(workingDir, tmpFileBaseName + "-1" + extension); if (File.Exists(generatedFile)) { try { File.Delete(outputFilePath); File.Move(generatedFile, outputFilePath); } catch (UnauthorizedAccessException) { if (controller_ != null) controller_.showUnauthorizedError(outputFilePath); } catch (IOException) { if (controller_ != null) controller_.showIOError(outputFilePath); } outputFileNames.Add(outputFilePath); } } else { string outputFilePathBaseName = Path.Combine(Path.GetDirectoryName(outputFilePath), Path.GetFileNameWithoutExtension(outputFilePath)); for (int i = 1; i <= page; ++i) { string generatedFile = Path.Combine(workingDir, tmpFileBaseName + "-" + i + extension); if (File.Exists(generatedFile)) { try { File.Delete(outputFilePathBaseName + "-" + i + extension); File.Move(generatedFile, outputFilePathBaseName + "-" + i + extension); } catch (UnauthorizedAccessException) { if (controller_ != null) controller_.showUnauthorizedError(outputFilePath); } catch (IOException) { if (controller_ != null) controller_.showIOError(outputFilePath); } outputFileNames.Add(outputFilePathBaseName + "-" + i + extension); } } } // ソース埋め込み if (Properties.Settings.Default.embedTeXSource && inputextension == ".tex") { try { using (var source = new FileStream(inputTeXFilePath, FileMode.Open, FileAccess.Read)) { var buf = new byte[source.Length]; source.Read(buf, 0, (int)source.Length); // エンコードの決定 var enc = KanjiEncoding.CheckBOM(buf); if (enc == null) { var encs = KanjiEncoding.GuessKajiEncoding(buf); var inpenc = GetInputEncoding(); if (encs.Count() != 0) enc = encs[0]; else enc = inpenc; foreach (var e in encs) { if (inpenc.CodePage == e.CodePage) { enc = inpenc; break; } } } var srctext = enc.GetString(buf); foreach (var f in outputFileNames) { TeXSource.EmbedSource(f, srctext); } } } // 例外は無視 catch (Exception) { } } if (controller_ != null) { foreach (var w in warnngs) controller_.appendOutput("TeX2img: " + w + "\n"); if (error_ignored) controller_.errorIgnoredWarning(); } if (Properties.Settings.Default.previewFlag) { if (outputFileNames.Count > 0) Process.Start(outputFileNames[0]); } return true; }