/// <summary> /// Saves the image with the specified filename. /// </summary> /// <param name="filename">The filename.</param> /// <param name="imageCompression">The image compression.</param> /// <param name="quality">The quality.</param> /// <param name="imageFormat">The image format.</param> public void Save(string filename, FileCompression imageCompression, int quality, FileFormat imageFormat) { ImageFormat format; string mimeType = string.Empty; EncoderValue compression; compression = GetCompression(imageCompression); switch (imageFormat) { case FileFormat.Bmp: format = ImageFormat.Bmp; mimeType = "image/bmp"; break; case FileFormat.Emf: format = ImageFormat.Emf; mimeType = "image/x-emf"; break; case FileFormat.Exif: format = ImageFormat.Exif; mimeType = "image/jpeg"; break; case FileFormat.Gif: format = ImageFormat.Gif; mimeType = "image/gif"; compression = EncoderValue.CompressionNone; break; case FileFormat.Jpeg: format = ImageFormat.Jpeg; mimeType = "image/jpeg"; break; case FileFormat.Png: format = ImageFormat.Png; mimeType = "image/png"; break; case FileFormat.Tiff: format = ImageFormat.Tiff; mimeType = "image/tiff"; break; case FileFormat.Wmf: format = ImageFormat.Wmf; mimeType = "image/x-wmf"; break; } if (mimeType == "image/tiff" && compression != EncoderValue.CompressionNone) { throw new Exception("Only LZW compression is allowed with TIFF format."); } ImageCodecInfo encoder = GetEncoderInfo(mimeType); if (encoder == null) { throw new Exception("Encoder not found. Try another format."); } System.Drawing.Imaging.EncoderParameters parameters = new EncoderParameters(2); EncoderParameter param1 = new EncoderParameter(Encoder.Compression, (long)compression); parameters.Param[0] = param1; EncoderParameter param2 = new EncoderParameter(Encoder.Quality, quality); parameters.Param[1] = param2; if (_g != null) { _g.Dispose(); } _image.Save(filename, encoder, parameters); }
// <summary> // Gets the full path of the file after it was saved by FileManager to the internal file storage. // </summary> //public FileInfo GetFileInfo() //{ // return FileManager.GetInfo(this.Parameters["FileRelativePath"].ToString()); //} /// <summary> /// Opens the file contents as a readable stream. /// </summary> /// <param name="subLocation"></param> /// <param name="compression"></param> /// <returns></returns> public Stream OpenContents(string subLocation = null, FileCompression compression = FileCompression.None) { if (string.IsNullOrEmpty(this.Location)) { throw new InvalidOperationException("The delivery file does not have a valid file location. Make sure it has been downloaded properly."); } return(FileManager.Open( location: subLocation != null ? Path.Combine(this.Location, subLocation) : this.Location, compression: compression )); }
private static EncoderValue GetCompression(FileCompression compression) { switch (compression) { case FileCompression.CCITT3: return(EncoderValue.CompressionCCITT3); case FileCompression.CCITT4: return(EncoderValue.CompressionCCITT4); case FileCompression.LZW: return(EncoderValue.CompressionLZW); case FileCompression.None: return(EncoderValue.CompressionNone); case FileCompression.Rle: return(EncoderValue.CompressionRle); } return(EncoderValue.CompressionNone); }
public void Export() { List <UserExportInfo> lu = JsonDeserialize <List <UserExportInfo> >(Common.GetRequest("userInfoList")); List <string> ls = JsonDeserialize <List <string> >(Common.GetRequest("amountNameList")); for (int i = 0; i < ls.Count; i++) //外循环是循环的次数 { for (int j = ls.Count - 1; j > i; j--) //内循环是 外循环一次比较的次数 { if (ls[i] == ls[j]) { ls.RemoveAt(j); } } } List <FileInfo> li = new List <FileInfo>(); //string AUserID = "110,108"; string fileName = ""; string path = ""; for (int i = 0; i < ls.Count; i++) { List <UserExportInfo> luTemp = lu.Where(m => m.AmountName == ls[i]).ToList(); string aae = lu[i].AnswerID.ToString(); StringBuilder builder; FileInfo file; StreamWriter sw; GetToWord(luTemp, out fileName, out path, out builder, out file, out sw, li.Count + 1); sw.Write(builder); sw.Close(); li.Add(file); } fileName = DateTime.Now.ToString("yyyyMMddhhmm") + "_Download.zip"; //重新赋值为zip文件名称 path = Server.MapPath("~/xls_down/" + fileName + ".xls"); FileCompression.Compress(li, path, 5, 5); //压缩 Response.Clear(); Response.Buffer = true; this.EnableViewState = false; Response.Charset = "utf-8"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.ContentType = "application/octet-stream"; Response.WriteFile(path); Response.Flush(); Response.Close(); Response.End(); }
/// <summary> /// Constructs a new instance of UltimaPackageFile. /// </summary> /// <param name="package">Pacakge that contains this file.</param> /// <param name="reader">Reader to read from.</param> public UltimaPackageFile( UltimaPackage package, BinaryReader reader ) { _Package = package; _FileAddress = reader.ReadInt64(); _FileAddress += reader.ReadInt32(); _CompressedSize = reader.ReadInt32(); _DecompressedSize = reader.ReadInt32(); _FileNameHash = reader.ReadUInt64(); reader.ReadInt32(); // Header hash switch ( reader.ReadInt16() ) { case 0: _Compression = FileCompression.None; break; case 1: _Compression = FileCompression.Zlib; break; } }
/// <summary> /// Constructs a new instance of UltimaPackageFile. /// </summary> /// <param name="package">Pacakge that contains this file.</param> /// <param name="reader">Reader to read from.</param> public UltimaPackageFile(UltimaPackage package, BinaryReader reader) { _Package = package; _FileAddress = reader.ReadInt64(); _FileAddress += reader.ReadInt32(); _CompressedSize = reader.ReadInt32(); _DecompressedSize = reader.ReadInt32(); _FileNameHash = reader.ReadUInt64(); reader.ReadInt32(); // Header hash switch (reader.ReadInt16()) { case 0: _Compression = FileCompression.None; break; case 1: _Compression = FileCompression.Zlib; break; } }
/// <summary> /// 将一个目录下的PP资源包进行解包 /// </summary> /// <param name="kppDestinationFilePath">KPP资源文件路径</param> /// <exception cref="ArgumentNullException">参数不能为空</exception> /// <exception cref="System.IO.FileNotFoundException">目标文件不存在</exception> /// <exception cref="BadImageFormatException">错误的KPP资源包格式</exception> /// <exception cref="UnSupportedSectionTypeException">不支持的数据节类型</exception> public static KPPDataStructure UnPack(string kppDestinationFilePath) { if (string.IsNullOrEmpty(kppDestinationFilePath)) { throw new ArgumentNullException("kppDestinationFilePath"); } if (!File.Exists(kppDestinationFilePath)) { throw new System.IO.FileNotFoundException("#Current file cannot be find, file: " + kppDestinationFilePath); } byte[] data = File.ReadAllBytes(kppDestinationFilePath); using (MemoryStream stream = new MemoryStream(data)) { KPPDataHead head = new KPPDataHead(); head.UnPack(stream); ushort sectionCount = head.GetField <ushort>("SectionCount"); Dictionary <byte, IKPPDataResource> sections = new Dictionary <byte, IKPPDataResource>(); for (int i = 0; i < sectionCount; i++) { byte sectionId = (byte)stream.ReadByte(); //reset position. stream.Position = stream.Position - 1; Type sectionType; if (!_sections.TryGetValue(sectionId, out sectionType)) { throw new UnSupportedSectionTypeException("#Current data section type cannot be supported. #id: " + sectionId); } IKPPDataResource section = (IKPPDataResource)sectionType.GetTypeInfo().Assembly.CreateInstance(sectionType.FullName); section.UnPack(stream); sections.Add(sectionId, section); } byte[] zipData = new byte[data.Length - stream.Position]; Buffer.BlockCopy(data, (int)stream.Position, zipData, 0, zipData.Length); Crc32 crc = new Crc32(); crc.Reset(); crc.Update(zipData); if (head.GetField <long>("CRC") != crc.Value) { throw new BadImageFormatException("#Bad image format of zipped stream CRC."); } IDictionary <string, byte[]> files = FileCompression.Decompress(zipData); return(new KPPDataStructure(head, sections, files)); } }
private void Compress() { var fileToCompress = new FileInfo(FileName); _compression = FileCompression.GZip; using (var originalFileStream = fileToCompress.OpenRead()) { using (var compressedFileStream = File.Create(GetCompressedFileName())) { using (var compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress, true)) { originalFileStream.CopyTo(compressionStream); } Trace.WriteLine($"{_logPrefix} Compressed {fileToCompress.Name} from {fileToCompress.Length} to {compressedFileStream.Length} bytes."); } } }
/// <summary> /// Opens the file represented by the FileInfo object. /// </summary> public static Stream Open(FileInfo fileInfo, FileCompression compression = FileCompression.None) { Stream stream; // Archive opening if (fileInfo.ArchiveLocation != null) { if (fileInfo.ArchiveType == ArchiveType.Zip) { FileStream zipStream = File.OpenRead(fileInfo.ArchiveLocation); ZipFile zipFile = new ZipFile(zipStream); ZipEntry zipEntry = zipFile.GetEntry(fileInfo.FileName); stream = zipFile.GetInputStream(zipEntry); } else { throw new NotImplementedException("Only zip archives supported at this time."); } } else { stream = File.OpenRead(fileInfo.FullPath); } // Decompression if (compression != FileCompression.None) { if (compression == FileCompression.Gzip) { stream = new GZipInputStream(stream); } else { throw new NotImplementedException("Only gzip compression supported at this time."); } } else { // Nothing to do here, since we already opened the file stream } return(stream); }
protected SocketStateState(ISocketState state, SocketClient client, ServerListener listener) { State = state; Client = client; Server = listener; if (client == null) { Encrypter = Server.MessageEncryption; FileCompressor = Server.FileCompressor; FolderCompressor = Server.FolderCompressor; } if (Server == null) { Encrypter = client.MessageEncryption; FileCompressor = client.FileCompressor; FolderCompressor = client.FolderCompressor; } }
public void CompressTest() { string fileName = Environment.CurrentDirectory + "\\" + "TestFile.txt"; var fileInfo = new FileInfo(fileName); StreamWriter streamWriter = fileInfo.CreateText(); streamWriter.WriteLine("AAAAA"); streamWriter.Flush(); streamWriter.Close(); string zipFileName = Environment.CurrentDirectory + "\\" + "TestFile.zip"; string password = "******"; bool expected = true; bool actual; actual = FileCompression.Compress(fileInfo, zipFileName, password, null); Assert.AreEqual(expected, actual); fileInfo = new FileInfo(zipFileName); Assert.IsTrue(fileInfo.Exists); }
public void HttpPostDataTest() { var fileName = System.Environment.CurrentDirectory + "\\upload.xml"; var zipName = System.Environment.CurrentDirectory + "\\upload.zip"; var license = "71C304D6-6E75-2370-0B49-8794CE8452D9"; var fileInfo = new FileInfo(fileName); var fileStream = fileInfo.AppendText(); fileStream.WriteLine(@"<?xml version=""1.0""?>"); fileStream.WriteLine(@"<DemandForce licenseKey=""71C304D6-6E75-2370-0B49-8794CE8452D9"" dFLinkVersion=""3.7.119"" >"); fileStream.WriteLine(@"<Business>"); fileStream.WriteLine(@" <Customer id=""7"" parentId=""7"" provider=""3"" firstVisit=""2009-08-04T07:26:05Z"" insuranceType=""Other"">"); fileStream.WriteLine(@" <Demographics firstName=""Maria"" lastName=""Cintron"" gender=""2"" birthday=""1984-04-01T00:00:00Z"" />"); fileStream.WriteLine(@" </Customer>"); fileStream.WriteLine(@"</Business>"); fileStream.WriteLine(@"</DemandForce>"); fileStream.Flush(); fileStream.Close(); FileCompression.Compress(fileInfo, zipName, license, null); var zipInfo = new FileInfo(zipName); long size = zipInfo.Length; var url = "https://dflink.sandbox.demandforced3.com/upload/1.0/xml.jsp"; var timeOut = 30 * 1000; var fileKeyName = "upload"; var filePathName = zipName; NameValueCollection stringDict = new NameValueCollection(); stringDict.Add("user", "*****@*****.**"); stringDict.Add("pass", string.Empty); stringDict.Add("license", license); string actual = HttpUtils.PostFormData(url, timeOut, fileKeyName, filePathName, stringDict); Assert.IsTrue(actual.Contains("zip with size of " + size.ToString() + " bytes. BusinessId =")); }
public static void Main(string[] args) { var options = new Options(); if (Parser.Default.ParseArguments(args, options)) { switch (options.Action) { case Options.Actions.Compress: FileCompression.CompressFile(options.InputFile, options.OutputFile); Console.WriteLine("Complete."); break; case Options.Actions.Decompress: FileCompression.ExtractFile(options.InputFile, options.OutputFile); Console.WriteLine("Complete."); break; default: Console.WriteLine("Error, you shouldn't see this. Contact the developer."); break; } } }
public void ExportData(HttpContext context) { List <UserExportInfo> lu = JsonDeserialize <List <UserExportInfo> >(Common.GetRequest("userInfoList")); List <string> ls = JsonDeserialize <List <string> >(Common.GetRequest("amountNameList")); for (int i = 0; i < ls.Count; i++) //外循环是循环的次数 { for (int j = ls.Count - 1; j > i; j--) //内循环是 外循环一次比较的次数 { if (ls[i] == ls[j]) { ls.RemoveAt(j); } } } List <FileInfo> li = new List <FileInfo>(); //string AUserID = "110,108"; string fileName; string path; for (int i = 0; i < ls.Count; i++) { List <UserExportInfo> luTemp = lu.Where(m => m.AmountName == ls[i]).ToList(); string aae = lu[i].AnswerID.ToString(); StringBuilder builder; FileInfo file; StreamWriter sw; GetToWord(luTemp, out fileName, out path, out builder, out file, out sw); sw.Write(builder); sw.Close(); li.Add(file); } fileName = DateTime.Now.ToString("yyyyMMddhhmm") + "_Download.zip";//重新赋值为zip文件名称 path = context.Server.MapPath("~/xls_down/" + fileName + ".xls"); try { FileCompression.Compress(li, path, 5, 5);//压缩 //context.Response.Clear(); //context.Response.Buffer = true; //context.Response.Charset = "utf-8"; //context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //context.Response.ContentType = "application/octet-stream"; //context.Response.WriteFile(path); //context.Response.Flush(); ////context.Response.Close(); //context.Response.End(); context.Response.ContentType = "application/zip"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //Byte[] bytes = new Byte[fs.Length]; fs.Close(); MemoryStream ms = new MemoryStream(); FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); ms.Write(bytes, 0, (int)file.Length); file.Close(); ms.Close(); context.Response.Write(ms.GetBuffer()); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { throw; } }
public static string GetExtension(this FileCompression value) { FileCompressionAttribute[] attributes = (FileCompressionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(FileCompressionAttribute), false); return((attributes.Length > 0) ? attributes[0].Extension : ""); }
private bool SaveChunk(ChunkColumn chunk) { File.WriteAllBytes(_folder + "/" + chunk.X + "." + chunk.Z + ".cfile", FileCompression.Compress(chunk.Export())); return(true); }
// Open operations // ========================================= /// <summary> /// Opens a file from the specified location. /// </summary> /// <param name="location">Relative location of file in the FileManager system.</param> public static Stream Open(string location, ArchiveType archiveType = ArchiveType.None, FileCompression compression = FileCompression.None) { return(Open(GetInfo(location, archiveType), compression)); }
protected abstract Result <int, ErrorCodes?> Execute( FileCompression compression, string inputFile, string outputFile);
protected void btn_import_07_click(object sender, EventArgs e) { //try //{ List <UserExportInfo> lu = JsonDeserialize <List <UserExportInfo> >(Request["userInfoList"]); List <string> ls = JsonDeserialize <List <string> >(Request["amountNameList"]); for (int i = 0; i < ls.Count; i++) //外循环是循环的次数 { for (int j = ls.Count - 1; j > i; j--) //内循环是 外循环一次比较的次数 { if (ls[i] == ls[j]) { ls.RemoveAt(j); } } } List <FileInfo> li = new List <FileInfo>(); //string AUserID = "110,108"; string fileName = ""; string path = ""; for (int i = 0; i < ls.Count; i++) { List <UserExportInfo> luTemp = lu.Where(m => m.AmountName == ls[i]).ToList(); string aae = lu[i].AnswerID.ToString(); StringBuilder builder = new StringBuilder(); FileInfo file = null; StreamWriter sw; if (ls[i].IndexOf("Rutter儿童行为问卷") > -1) { GetToWordS(luTemp, out fileName, out path, out builder, out file, out sw); } else { GetToWord(luTemp, out fileName, out path, out builder, out file, out sw, li.Count + 1); } sw.Write(builder); sw.Close(); li.Add(file); } fileName = DateTime.Now.ToString("yyyyMMddhhmm") + "_Download.zip"; //重新赋值为zip文件名称 path = Server.MapPath("~/xls_down/" + fileName + ".xls"); FileCompression.Compress(li, path, 5, 5); //压缩 Response.Clear(); Response.Buffer = true; this.EnableViewState = false; Response.Charset = "utf-8"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.ContentType = "application/octet-stream"; Response.WriteFile(path); Response.Flush(); //Response.Close(); HttpContext.Current.Response.End(); //} //catch (Exception ex) //{ // Response.End(); //} //finally //{ // HttpContext.Current.Response.End(); //} }
protected override Result <int, ErrorCodes?> Execute(FileCompression compression, string inputFile, string outputFile) { return(compression.CompressFiles(inputFile, outputFile)); }