//使用GZIP压缩文件的方法 public static void GZipFile(string sourcefilename, string zipfilename) { using (FileStream srcFile = File.OpenRead(sourcefilename)) { byte[] FileData = new byte[srcFile.Length]; srcFile.Read(FileData, 0, (int)srcFile.Length); srcFile.Close(); using (GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename, FileMode.Create, FileAccess.Write))) { zipFile.Write(FileData, 0, FileData.Length); zipFile.Close(); } } }
/// <summary> /// Gzip压缩 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static byte[] GzipCompress(byte[] bytes) { using (MemoryStream ms = new MemoryStream()) { using (GZipOutputStream gzip = new GZipOutputStream(ms)) { gzip.Write(bytes, 0, bytes.Length); gzip.Close(); byte[] press = ms.ToArray(); return(press); } } }
public void DoubleFooter() { var memStream = new TrackedMemoryStream(); var s = new GZipOutputStream(memStream); s.Finish(); Int64 length = memStream.Length; #if NET451 s.Close(); #elif NETCOREAPP1_0 s.Dispose(); #endif Assert.AreEqual(length, memStream.ToArray().Length); }
public static byte[] Compress(byte[] bytes) { if (bytes == null || bytes.Length <= 0) { return(bytes); } MemoryStream ms = null; GZipOutputStream gzos = null; try { ms = new MemoryStream(); gzos = new GZipOutputStream(ms); gzos.Write(bytes, 0, bytes.Length); gzos.Close(); gzos = null; return(ms.ToArray()); } catch (Exception e) { Debugger.LogError("Data can not be compressed: " + e); return(null); } finally { if (gzos != null) { gzos.Close(); } if (ms != null) { ms.Close(); } } }
/// <summary> /// 压缩字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] CompressString(string rawData) { MemoryStream ms = new MemoryStream(); GZipOutputStream compressedzipStream = new GZipOutputStream(ms); byte[] data = Encoding.UTF8.GetBytes(rawData);//Util.stringToBytes(strData); int size = data.Length; compressedzipStream.Write(data, 0, data.Length); compressedzipStream.Finish(); compressedzipStream.Close(); byte[] result = ms.ToArray(); return(result); }
/// <summary> /// 压缩 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Compress(string input) { string result = string.Empty; byte[] buffer = Encoding.UTF8.GetBytes(input); using (MemoryStream outputStream = new MemoryStream()) { using (GZipOutputStream zipStream = new GZipOutputStream(outputStream)) { zipStream.Write(buffer, 0, buffer.Length); zipStream.Close(); } return(Convert.ToBase64String(outputStream.ToArray())); } }
private static void Compress(string filePath) { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Blue; Console.Write("----------------------------压缩----------------------------\n"); byte[] data = File.ReadAllBytes(filePath); MemoryStream ms = new MemoryStream(); Stream stream = new GZipOutputStream(ms); stream.Write(data, 0, data.Length); stream.Close(); ms.Close(); byte[] compressedData = ms.ToArray(); Encrypt(ref compressedData); File.WriteAllBytes(filePath.Replace(".txt", ""), compressedData); }
public void WriteAfterClose() { var memStream = new TrackedMemoryStream(); var s = new GZipOutputStream(memStream); s.Close(); try { s.WriteByte(7); Assert.Fail("Write should fail"); } catch { } }
public static void ZipFile(Stream sm, string dfile) { try { GZipOutputStream s = new GZipOutputStream(File.Create(dfile)); byte[] writeData = new byte[sm.Length]; sm.Read(writeData, 0, (int)sm.Length); s.Write(writeData, 0, writeData.Length); s.Close(); sm.Close(); } catch (Exception) { throw; } }
public virtual void Send(Stream s) { s.Write(BitConverter.GetBytes((ushort)type), 0, sizeof(ushort)); if (payload != null) { MemoryStream writeBuffer = new MemoryStream(1); payload.WriteToStream(writeBuffer); if (writeBuffer.Length < 150) { s.WriteByte(0); s.Write(BitConverter.GetBytes((uint)writeBuffer.Length), 0, sizeof(uint)); s.Write(writeBuffer.GetBuffer(), 0, (int)writeBuffer.Length); #if DEBUG Console.WriteLine("S" + writeBuffer.Length + ": " + type); #endif } else { int uncompressed = (int)writeBuffer.Length; writeBuffer = new MemoryStream(1); GZipOutputStream comp = new GZipOutputStream(writeBuffer, 5); comp.IsStreamOwner = false; payload.WriteToStream(comp); comp.Close(); s.WriteByte(1); s.Write(BitConverter.GetBytes((uint)writeBuffer.Length), 0, sizeof(uint)); s.Write(writeBuffer.GetBuffer(), 0, (int)writeBuffer.Length); #if DEBUG Console.WriteLine("S" + writeBuffer.Length + "(uncompressed" + uncompressed + ": " + type); #endif } } else { s.WriteByte(0); s.Write(BitConverter.GetBytes((uint)0), 0, sizeof(uint)); #if DEBUG if (type != RequestType.Bancho_Ping && type != RequestType.Osu_Pong) { Console.WriteLine("S0: " + type); } #endif } s.Flush(); }
public static string TestZip(string data) { FileStream fs = new FileStream("D:\\test.zip", FileMode.Create); GZipOutputStream zos = new GZipOutputStream(fs); byte[] buf = StrUtil.ToByteArray(data); zos.Write(buf, 0, buf.Length); zos.Flush(); fs.Flush(); //FileStream fs2 = new FileStream("D:\\test2.zip", FileMode.Create); //StreamUtils.Copy(fs,fs2,new byte[1024]); //fs2.Flush(); //fs2.Close(); MemoryStream s1 = new MemoryStream(); //StreamUtils.Copy(fs, s1, new byte[1024]); fs.CopyTo(s1); s1.Seek(0, SeekOrigin.Begin); zos.Close(); fs.Close(); //fs = new FileStream("D:\\test.zip", FileMode.Open); //MemoryStream s1 = new MemoryStream(); //StreamUtils.Copy(fs,s1,new byte[1024]); //s1.Seek(0, SeekOrigin.Begin); GZipInputStream zis = new GZipInputStream(s1); MemoryStream rs = new MemoryStream(); buf = new byte[1024]; int size = 0; while ((size = zis.Read(buf, 0, buf.Length)) > 0) { rs.Write(buf, 0, size); } zis.Close(); fs.Close(); return(StrUtil.FromByteArray(rs.ToArray())); }
public static byte[] CatHomeMainZ2(byte[] data, byte[] home, byte[] info, bool isCompress = false) { MemoryStream memoryStream = null; CryptoStream cryptoStream = null; byte[] result; try { ICryptoTransform cryptoTransform = new RijndaelManaged { Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC, KeySize = 256, BlockSize = 256 }.CreateEncryptor(home, info); memoryStream = new MemoryStream(); cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write); if (isCompress) { GZipOutputStream gzipOutputStream = new GZipOutputStream(cryptoStream); gzipOutputStream.Write(data, 0, data.Length); gzipOutputStream.Close(); } else { cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); } result = memoryStream.ToArray(); } catch (Exception) { result = null; } finally { if (memoryStream != null) { memoryStream.Close(); } if (cryptoStream != null) { cryptoStream.Close(); } } return(result); }
/// <summary> /// 制作压缩包(单个文件压缩) /// </summary> /// <param name="srcFileName">原文件</param> /// <param name="zipFileName">压缩文件</param> /// <param name="zipEnum">压缩算法枚举</param> /// <returns>压缩成功标志</returns> public static bool ZipFile(string srcFileName, string zipFileName, ZipEnum zipEnum) { bool flag = true; try { switch (zipEnum) { case ZipEnum.BZIP2: FileStream inStream = File.OpenRead(srcFileName); FileStream outStream = File.Open(zipFileName, FileMode.Create); //参数true表示压缩完成后,inStream和outStream连接都释放 BZip2.Compress(inStream, outStream, 4096); inStream.Close(); outStream.Close(); break; case ZipEnum.GZIP: FileStream srcFile = File.OpenRead(srcFileName); GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipFileName, FileMode.Create)); byte[] fileData = new byte[srcFile.Length]; srcFile.Read(fileData, 0, (int)srcFile.Length); zipFile.Write(fileData, 0, fileData.Length); srcFile.Close(); zipFile.Close(); break; default: break; } } catch { flag = false; } return(flag); }
/// <summary> /// 压缩字符串 /// </summary> public static string Compress(string source) { byte[] data = Encoding.UTF8.GetBytes(source); MemoryStream ms = null; using (ms = new MemoryStream()) { using (Stream stream = new GZipOutputStream(ms)) { try { stream.Write(data, 0, data.Length); } finally { stream.Close(); ms.Close(); } } } return(Convert.ToBase64String(ms.ToArray())); }
/// <summary> /// 压缩文件 /// </summary> /// <param name="resourceFileName">源文件名(包含路径)</param> /// <param name="targetZipName">压缩文件名</param> /// <returns></returns> public static bool CreateZipFile(string resourceFileName, string targetZipName) { if (string.IsNullOrWhiteSpace(resourceFileName)) { throw new ArgumentNullException("resourceFileName"); } if (string.IsNullOrWhiteSpace(targetZipName)) { throw new ArgumentNullException("targetZipName"); } if (Path.GetExtension(targetZipName).ToLower() != ".gz") { throw new ArgumentException("Formate of extension is error"); } FileStream fStream = default(FileStream); Stream gzOutputStream = default(Stream); try { fStream = File.OpenRead(resourceFileName); byte[] writeData = new byte[fStream.Length]; fStream.Read(writeData, 0, (int)fStream.Length); gzOutputStream = new GZipOutputStream(File.Create(targetZipName)); gzOutputStream.Write(writeData, 0, writeData.Length); } finally { if (fStream != null) { fStream.Flush(); fStream.Close(); } if (gzOutputStream != null) { gzOutputStream.Flush(); gzOutputStream.Close(); } } return(File.Exists(targetZipName)); }
public static byte[] CompressGZip(byte[] _bytes) { if (_bytes.Length == 0) { return(m_emptyBytes); } using (MemoryStream msIn = new MemoryStream()){ using (GZipOutputStream swZip = new GZipOutputStream(msIn)){ swZip.Write(_bytes, 0, _bytes.Length); // close to finish compress swZip.Close(); return(msIn.ToArray()); } } }
public void WriteAfterClose() { var memStream = new TrackedMemoryStream(); var s = new GZipOutputStream(memStream); #if NET451 s.Close(); #elif NETCOREAPP1_0 s.Dispose(); #endif try { s.WriteByte(7); Assert.Fail("Write should fail"); } catch { } }
/// <summary> /// 将字节数组压缩,返回压缩后的字节数组 /// </summary> public static byte[] Compress(byte[] bytes) { if (bytes == null) { return(null); } MemoryStream ms = new MemoryStream(); GZipOutputStream stream = new GZipOutputStream(ms); stream.Write(bytes, 0, bytes.Length); stream.Close(); byte[] result = ms.ToArray(); ms.Close(); return(result); }
public static Stream CompressStream(Stream streamIn) { MemoryStream streamOut = new MemoryStream(); byte[] buffer = new byte[4096]; using (GZipOutputStream compressionStream = new GZipOutputStream(streamOut)) { //GZipOutputStream compressionStream = new GZipOutputStream(streamOut); compressionStream.SetLevel(5); //good balance between speed of compression and actual packed bytes compressionStream.IsStreamOwner = false; StreamUtils.Copy(streamIn, compressionStream, buffer); compressionStream.Close(); } streamOut.Flush(); streamOut.Position = 0; //reset the pointer return(streamOut); }
/// <summary> /// 生成 ***.tar.gz 文件 /// </summary> /// <param name="i_BasePath">文件基目录(源文件、生成文件所在目录)</param> /// <param name="i_SourceFolderName">待压缩的源文件夹名</param> public static string CreatTarGzArchive(string i_BasePath, string i_SourceFolderName, string i_TargetFolderName) { DateTime v_StartDT = DateTime.Now; if (string.IsNullOrEmpty(i_BasePath) || string.IsNullOrEmpty(i_SourceFolderName) || !System.IO.Directory.Exists(i_BasePath) || !System.IO.Directory.Exists(Path.Combine(i_BasePath, i_SourceFolderName))) { return(string.Empty); } Environment.CurrentDirectory = i_BasePath; string strSourceFolderAllPath = Path.Combine(i_BasePath, i_SourceFolderName); string strOupFileAllPath = Path.Combine(i_BasePath, i_TargetFolderName + ".tar.gz"); Stream outTmpStream = new FileStream(strOupFileAllPath, FileMode.OpenOrCreate); // 注意此处源文件大小大于4096KB Stream outStream = new GZipOutputStream(outTmpStream); TarArchive archive = TarArchive.CreateOutputTarArchive(outStream, TarBuffer.DefaultBlockFactor); // 打包目标文件夹下的所有文件 String[] files = Directory.GetFiles(strSourceFolderAllPath); foreach (String name in files) { TarEntry entry = TarEntry.CreateEntryFromFile(name); entry.Name = name.Substring(name.LastIndexOf('\\') + 1); archive.WriteEntry(entry, true); } // 打包目标文件夹,包含目标文件夹 //TarEntry entry = TarEntry.CreateEntryFromFile(strSourceFolderAllPath); //archive.WriteEntry(entry, true); if (archive != null) { archive.Close(); } outTmpStream.Close(); outStream.Close(); Console.WriteLine("ypn....CreatTarGzArchive,耗时 {0} 秒", DateTime.Now.Subtract(v_StartDT).TotalSeconds); return(strOupFileAllPath); }
/// zip a utf8 string using gzip into a base64 encoded string public static string ZipString(string ATextToCompress) { Byte[] originalText = Encoding.UTF8.GetBytes(ATextToCompress); MemoryStream memoryStream = new MemoryStream(); GZipOutputStream gzStream = new GZipOutputStream(memoryStream); gzStream.Write(originalText, 0, originalText.Length); gzStream.Flush(); gzStream.Finish(); memoryStream.Position = 0; Byte[] compressedBuffer = new byte[memoryStream.Length]; memoryStream.Read(compressedBuffer, 0, compressedBuffer.Length); gzStream.Close(); return(Convert.ToBase64String(compressedBuffer)); }
public byte[] GZip(string text) { var buffer = Encoding.UTF8.GetBytes(text); using (var ms = new MemoryStream()) using (var zipStream = new GZipOutputStream(ms)) { zipStream.Write(buffer, 0, buffer.Length); zipStream.Close(); var compressed = ms.ToArray(); var gzBuffer = new byte[compressed.Length + 4]; Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return(gzBuffer); } }
}//end method /// <summary> /// Zips using a temporary file in the user's %TMP% folder. /// </summary> /// <param name="fileName"></param> /// <param name="streams"></param> /// <param name="names"></param> /// <returns></returns> public static Stream IOTarGz(String fileName, Stream[] streams, String[] names) { String tmpFileName = String.Format("{0}\\{1}", ConfigurationManager.AppSettings["ArchiveFolder"], fileName); Stream archiveStream = new FileStream(tmpFileName, FileMode.Open, FileAccess.ReadWrite); GZipOutputStream targetStream = new GZipOutputStream(archiveStream); TarArchive tarArchive = TarArchive.CreateOutputTarArchive(targetStream, TarBuffer.DefaultBlockFactor); var nameEnum = names.GetEnumerator(); foreach (var stream in streams) { nameEnum.MoveNext(); TarEntry entry = TarEntry.CreateEntryFromFile(nameEnum.Current.ToString()); tarArchive.WriteEntry(entry, true); } tarArchive.Close(); targetStream.Close(); archiveStream.Position = 0; archiveStream.Flush(); return(archiveStream); } //end method
public static string CompressFile(string filePath) { string filePathOut = filePath + ".gz"; FileStream fsIn = File.OpenRead(filePath); FileStream fsOut = File.Create(filePathOut); GZipOutputStream compressionStream = new GZipOutputStream(fsOut); compressionStream.SetLevel(5); //good balance between speed of compression and actual packed bytes compressionStream.IsStreamOwner = true; byte[] buffer = new byte[4096]; using (fsIn) { StreamUtils.Copy(fsIn, compressionStream, buffer); } compressionStream.Close(); return(filePathOut); }
/// <summary> /// GZip压缩 /// </summary> /// <param name="rawData"></param> /// <returns></returns> public static byte[] Compress(string input) { Byte[] byteInput = System.Text.Encoding.Default.GetBytes(input); //string类型转成byte[]: // MemoryStream ms = new MemoryStream(); // GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); // compressedzipStream.Write(byteInput, 0, input.Length); // compressedzipStream.Close(); // Console.WriteLine(ToHexString(ms.ToArray())); // return ToHexString(ms.ToArray());//123 ---> 1F8B08000000000004003334320600D263488803000000 using (MemoryStream ms = new MemoryStream()) { GZipOutputStream zipFile = new GZipOutputStream(ms); zipFile.Write(byteInput, 0, input.Length); zipFile.Close(); Console.WriteLine("压缩成功的数组转成16进制字符串为:" + ToHexString(ms.ToArray())); //1F8B0800D9BB835D00FF3334320600D263488803000000 // return ToHexString(ms.ToArray()); return(ms.ToArray()); } }
/// <summary> /// 对字符按照指定编码格式进行编码 </summary> /// <param name="str"> 待处理字符串 </param> /// <param name="encoding"> 编码格式 </param> /// <returns> 编码后的字节数组 </returns> public static sbyte[] compress(string str, string encoding) { if (string.ReferenceEquals(str, null) || str.Length == 0) { return(null); } System.IO.MemoryStream @out = new System.IO.MemoryStream(); GZipOutputStream gzip; try { gzip = new GZipOutputStream(@out); gzip.Write(Encoding.UTF8.GetBytes(str), 0, str.Length); gzip.Close(); } catch (Exception e) { Console.WriteLine(e); } return((sbyte[])(object)@out.ToArray()); }
public static string Create(string packageFolder, string outputFolder) { JObject manifest = PublicationManifest.LoadManifest(packageFolder); string packageName = manifest["name"] + "-" + manifest["version"] + ".tgz"; Directory.CreateDirectory(outputFolder); string outputFile = Path.Combine(outputFolder, packageName); Stream outStream = File.Create(outputFile); Stream gzoStream = new GZipOutputStream(outStream); TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream); AddDirectoryFilesToTar(tarArchive, packageFolder, true, "packages/"); tarArchive.Close(); gzoStream.Close(); outStream.Close(); return(outputFile); }
public bool GZipFile(string sourcefilename, string zipfilename) { bool flag; FileStream stream = File.OpenRead(sourcefilename); GZipOutputStream stream2 = new GZipOutputStream(File.Open(zipfilename.Replace(".txt", ".gz"), FileMode.Create)); try { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); stream2.Write(buffer, 0, buffer.Length); flag = true; } catch (Exception exception) { Console.WriteLine(exception.Message); flag = false; } stream.Close(); stream2.Close(); return(flag); }
public static bool GZipFile(string sourcefilename, string zipfilename) { bool blResult;//表示压缩是否成功的返回结果 //为源文件创建读取文件的流实例 FileStream srcFile = File.OpenRead(sourcefilename); //为压缩文件创建写入文件的流实例, GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename, FileMode.Create)); try { byte[] FileData = new byte[srcFile.Length]; //创建缓冲数据 srcFile.Read(FileData, 0, (int)srcFile.Length); //读取源文件 zipFile.Write(FileData, 0, FileData.Length); //写入压缩文件 blResult = true; } catch (Exception ee) { Console.WriteLine(ee.Message); blResult = false; } srcFile.Close(); //关闭源文件 zipFile.Close(); //关闭压缩文件 return(blResult); }
/// <summary> /// Compress the specified sBuffer. /// </summary> /// <param name="sBuffer">S buffer.</param> public static string Compress(string sBuffer) { string b64 = null; MemoryStream rawDataStream = null; GZipOutputStream gzipOut = null; try { rawDataStream = new MemoryStream(); gzipOut = new GZipOutputStream(rawDataStream); byte[] sIn = UTF8Encoding.UTF8.GetBytes(sBuffer); gzipOut.IsStreamOwner = false; gzipOut.Write(sIn, 0, sIn.Length); gzipOut.Close(); byte[] compressed = rawDataStream.ToArray(); // data sent to the php service b64 = Convert.ToBase64String(compressed); } catch (Exception ex) { ConsoleEx.DebugLog("GZip compress error : " + ex.ToString()); } finally { if (gzipOut != null) { gzipOut.Dispose(); gzipOut = null; } if (rawDataStream != null) { rawDataStream.Dispose(); rawDataStream = null; } } return(b64); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void Compress(HttpRequest request, HttpResponse response) { Encoding encoding = Encoding.GetEncoding("windows-1252"); string enc, cacheFile = null, cacheKey = null, content = ""; StringWriter writer = new StringWriter(); byte[] buff = new byte[1024]; GZipOutputStream gzipStream; bool supportsGzip; // Set response headers response.ContentType = "text/css"; response.Charset = this.charset; response.Buffer = false; // Setup cache response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset)); // Check if it supports gzip enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower(); supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null; enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip"; // Setup cache info if (this.diskCache) { cacheKey = ""; foreach (CSSCompressItem item in this.items) { // Get last mod if (item.Type == CSSItemType.File) { DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value)); if (fileMod > this.lastUpdate) this.lastUpdate = fileMod; } cacheKey += item.Value; } cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey); if (this.gzipCompress) cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz"); else cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".css"); } // Use cached file disk cache if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); response.WriteFile(cacheFile); return; } foreach (CSSCompressItem item in this.items) { if (item.Type == CSSItemType.File) { StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8); string data; if (item.RemoveWhiteSpace) data = this.TrimWhiteSpace(reader.ReadToEnd()); else data = reader.ReadToEnd(); if (this.convertUrls) data = Regex.Replace(data, "url\\(['\"]?(?!\\/|http)", "$0" + PathUtils.ToUnixPath(Path.GetDirectoryName(item.Value)) + "/"); writer.Write(data); reader.Close(); } else { if (item.RemoveWhiteSpace) writer.Write(this.TrimWhiteSpace(item.Value)); else writer.Write(item.Value); } } content = writer.ToString(); // Generate GZIP'd content if (supportsGzip) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); if (this.diskCache && cacheKey != null) { try { // Gzip compress if (this.gzipCompress) { gzipStream = new GZipOutputStream(File.Create(cacheFile)); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } else { StreamWriter sw = File.CreateText(cacheFile); sw.Write(content); sw.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } // Write to stream response.WriteFile(cacheFile); } catch (Exception) { content = "/* Not cached */" + content; if (this.gzipCompress) { gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } else { response.Write(content); } } } else { content = "/* Not cached */" + content; gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } } else { content = "/* Not cached */" + content; response.Write(content); } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="response"></param> public void Compress(HttpRequest request, HttpResponse response) { Encoding encoding = Encoding.GetEncoding("windows-1252"); string enc, cacheFile = null, cacheKey = null, content = ""; StringWriter writer = new StringWriter(); byte[] buff = new byte[1024]; GZipOutputStream gzipStream; bool supportsGzip; // Set response headers response.ContentType = "text/javascript"; response.Charset = this.charset; response.Buffer = false; // Setup cache response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset)); // Check if it supports gzip enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower(); supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null; enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip"; // Setup cache info if (this.diskCache) { cacheKey = ""; foreach (JSCompressItem item in this.items) { // Get last mod if (item.Type == JSItemType.File) { DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value)); if (fileMod > this.lastUpdate) this.lastUpdate = fileMod; } cacheKey += item.Value; } cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey); if (this.gzipCompress) cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz"); else cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".js"); } // Use cached file disk cache if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); response.WriteFile(cacheFile); return; } foreach (JSCompressItem item in this.items) { if (item.Type == JSItemType.File) { if (!File.Exists(request.MapPath(item.Value))) { writer.WriteLine("alert('Could not load file: " + StringUtils.Escape(item.Value) + "');"); continue; } StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8); if (item.RemoveWhiteSpace) { JavaScriptMinifier jsMin = new JavaScriptMinifier(reader, writer); jsMin.Compress(); } else { writer.Write('\n'); writer.Write(reader.ReadToEnd()); writer.Write(";\n"); } reader.Close(); } else { if (item.RemoveWhiteSpace) { JavaScriptMinifier jsMin = new JavaScriptMinifier(new StringReader(item.Value), writer); jsMin.Compress(); } else { writer.Write('\n'); writer.Write(item.Value); writer.Write('\n'); } } } content = writer.ToString(); // Generate GZIP'd content if (supportsGzip) { if (this.gzipCompress) response.AppendHeader("Content-Encoding", enc); if (this.diskCache && cacheKey != null) { try { // Gzip compress if (this.gzipCompress) { gzipStream = new GZipOutputStream(File.Create(cacheFile)); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } else { StreamWriter sw = File.CreateText(cacheFile); sw.Write(content); sw.Close(); File.SetLastWriteTime(cacheFile, this.lastUpdate); } // Write to stream response.WriteFile(cacheFile); } catch (Exception) { content = "/* Not cached */" + content; if (this.gzipCompress) { gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } else { response.Write(content); } } } else { content = "/* Not cached */" + content; gzipStream = new GZipOutputStream(response.OutputStream); buff = encoding.GetBytes(content.ToCharArray()); gzipStream.Write(buff, 0, buff.Length); gzipStream.Close(); } } else { content = "/* Not cached */" + content; response.Write(content); } }