コード例 #1
1
ファイル: ZipHelper.cs プロジェクト: BlueInt32/bundle-report
        /// <summary>
        /// This function creates a zip
        /// </summary>
        /// <param name="filepaths">List of absolute system filepaths</param>
        /// <param name="zipFileName">Absolute desired systeme final zip filepath</param>
        /// <param name="compressionLevel">Compression level from 0 (no comp.) to 9 (best comp.)</param>
        /// <returns></returns>
        public StdResult<NoType> CreateZip(List<string> filepaths, string zipFileName, int compressionLevel)
        {
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
                {
                    s.SetLevel(9); // 0 - store only to 9 - means best compression

                    byte[] buffer = new byte[4096];

                    foreach (string file in filepaths)
                    {

                        // Using GetFileName makes the result compatible with XP
                        // as the resulting path is not absolute.
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                        // Setup the entry data as required.

                        // Crc and size are handled by the library for seakable streams
                        // so no need to do them here.

                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {

                            // Using a fixed size buffer here makes no noticeable difference for output
                            // but keeps a lid on memory usage.
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }

                    // Finish/Close arent needed strictly as the using statement does this automatically

                    // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                    // the created file would be invalid.
                    s.Finish();

                    // Close is important to wrap things up and unlock the file.
                    s.Close();
                    return StdResult<NoType>.OkResult;
                }
            }
            catch (Exception ex)
            {
                return StdResult<NoType>.BadResult(ex.Message);

                // No need to rethrow the exception as for our purposes its handled.
            }
        }
コード例 #2
0
ファイル: ZipUtilities.cs プロジェクト: rcichota/APSIM.Shared
        /// <summary>
        /// Zip all the specified files into the specified ZipFileName.
        /// </summary>
        public static string ZipFiles(IEnumerable<string> FilesToZip, string ZipFileName, string Password)
        {
            if (!File.Exists(ZipFileName))
                File.Delete(ZipFileName);

            ZipOutputStream Zip = new ZipOutputStream(File.Create(ZipFileName));
            if (Password != "")
                Zip.Password = Password;
            try
            {
                Zip.SetLevel(5); // 0 - store only to 9 - means best compression
                foreach (string FileName in FilesToZip)
                {
                    FileStream fs = File.OpenRead(FileName);

                    byte[] Buffer = new byte[fs.Length];
                    fs.Read(Buffer, 0, Buffer.Length);
                    fs.Close();

                    ZipEntry Entry = new ZipEntry(Path.GetFileName(FileName));
                    Zip.PutNextEntry(Entry);
                    Zip.Write(Buffer, 0, Buffer.Length);
                }
                Zip.Finish();
                Zip.Close();
                return ZipFileName;
            }
            catch (System.Exception)
            {
                Zip.Finish();
                Zip.Close();
                File.Delete(ZipFileName);
                throw;
            }
        }
コード例 #3
0
        //public static void ZipFile(string path, string file2Zip, string zipFileName, string zip, string bldgType)
        public static void ZipFile(string path, string file2Zip, string zipFileName)
        {
            //MemoryStream ms = InitializeGbxml(path + file2Zip, zip, bldgType) as MemoryStream;
            MemoryStream ms = InitializeGbxml(Path.Combine(path , file2Zip)) as MemoryStream;
 
            string compressedFile =Path.Combine(path, zipFileName);
            if (File.Exists(compressedFile))
            {
                File.Delete(compressedFile);
            }
            Crc32 objCrc32 = new Crc32();
            ZipOutputStream strmZipOutputStream = new ZipOutputStream(File.Create(compressedFile));
            strmZipOutputStream.SetLevel(9);

            byte[] gbXmlBuffer = new byte[ms.Length];
            ms.Read(gbXmlBuffer, 0, gbXmlBuffer.Length);

            ZipEntry objZipEntry = new ZipEntry(file2Zip);

            objZipEntry.DateTime = DateTime.Now;
            objZipEntry.Size = ms.Length;
            ms.Close();
            objCrc32.Reset();
            objCrc32.Update(gbXmlBuffer);
            objZipEntry.Crc = objCrc32.Value;
            strmZipOutputStream.PutNextEntry(objZipEntry);
            strmZipOutputStream.Write(gbXmlBuffer, 0, gbXmlBuffer.Length);
            strmZipOutputStream.Finish();
            strmZipOutputStream.Close();
            strmZipOutputStream.Dispose();
        }
コード例 #4
0
ファイル: ZipUtil.cs プロジェクト: WeDoCrm/PreDeployer
        // Compresses the supplied memory stream, naming it as zipEntryName, into a zip,
        // which is returned as a memory stream or a byte array.
        //
        public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName)
        {
            MemoryStream outputMemStream = new MemoryStream();
            ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

            zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

            ZipEntry newEntry = new ZipEntry(zipEntryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
            zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.

            outputMemStream.Position = 0;
            return outputMemStream;

            // Alternative outputs:
            // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.
            //byte[] byteArrayOut = outputMemStream.ToArray();

            // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
            //byte[] byteArrayOut = outputMemStream.GetBuffer();
            //long len = outputMemStream.Length;
        }
コード例 #5
0
ファイル: ZipHelper.cs プロジェクト: mokth/merpV3
        public static string GetZipFileName(string filename)
        {
            string zipfile = filename.Replace (".db", ".zip");
            try {

                using (ZipOutputStream s = new ZipOutputStream (File.Create (zipfile))) {
                    s.SetLevel (9); // 0 - store only to 9 - means best compression
                    byte[] buffer = new byte[4096];
                    ZipEntry entry = new ZipEntry (filename);
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry (entry);

                    using (FileStream fs = File.OpenRead (filename)) {
                        int sourceBytes;
                        do {
                            sourceBytes = fs.Read (buffer, 0, buffer.Length);
                            s.Write (buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                    s.Finish ();
                    s.Close ();
                }
            } catch (Exception ex) {
                zipfile = filename;
            }
            return zipfile;
        }
コード例 #6
0
ファイル: Zip.cs プロジェクト: shaunus84/through-shadows
	static public void CompressFolder(string aFolderName, string aFullFileOuputName, string[] ExcludedFolderNames, string[] ExcludedFileNames){
		// Perform some simple parameter checking.  More could be done
		// like checking the target file name is ok, disk space, and lots
		// of other things, but for a demo this covers some obvious traps.
		if (!Directory.Exists(aFolderName)) {
			Debug.Log("Cannot find directory : " + aFolderName);
			return;
		}

		try
		{
			string[] exFileNames = new string[0];
			string[] exFolderNames = new string[0];
			if(ExcludedFileNames != null) exFileNames = ExcludedFileNames;
			if(ExcludedFolderNames != null) exFolderNames = ExcludedFolderNames;
			// Depending on the directory this could be very large and would require more attention
			// in a commercial package.
			List<string> filenames = GenerateFolderFileList(aFolderName, null);
			
			//foreach(string filename in filenames) Debug.Log(filename);
			// 'using' statements guarantee the stream is closed properly which is a big source
			// of problems otherwise.  Its exception safe as well which is great.
			using (ZipOutputStream zipOut = new ZipOutputStream(File.Create(aFullFileOuputName))){
			zipOut.Finish();
			zipOut.Close();
			}
			using(ZipFile s = new ZipFile(aFullFileOuputName)){
					s.BeginUpdate();
					int counter = 0;
					//add the file to the zip file
				   	foreach(string filename in filenames){
						bool include = true;
						string entryName = filename.Replace(aFolderName, "");
						//Debug.Log(entryName);
						foreach(string fn in exFolderNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						foreach(string fn in exFileNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						if(include){
							s.Add(filename, entryName);
						}
						counter++;
					}
				    //commit the update once we are done
				    s.CommitUpdate();
				    //close the file
				    s.Close();
				}
		}
		catch(Exception ex)
		{
			Debug.Log("Exception during processing" + ex.Message);
			
			// No need to rethrow the exception as for our purposes its handled.
		}
	}
コード例 #7
0
ファイル: clsCompression.cs プロジェクト: wangshu/NY_HACK
 public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
 {
     if (!File.Exists(FileToZip))
     {
         throw new FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
     }
     FileStream fileStream = new FileStream(FileToZip, FileMode.Open, FileAccess.Read);
     FileStream baseOutputStream = File.Create(ZipedFile);
     ZipOutputStream zipOutputStream = new ZipOutputStream(baseOutputStream);
     ZipEntry entry = new ZipEntry("ZippedFile");
     zipOutputStream.PutNextEntry(entry);
     zipOutputStream.SetLevel(CompressionLevel);
     byte[] array = new byte[BlockSize];
     int num = fileStream.Read(array, 0, array.Length);
     zipOutputStream.Write(array, 0, num);
     try
     {
         while ((long)num < fileStream.Length)
         {
             int num2 = fileStream.Read(array, 0, array.Length);
             zipOutputStream.Write(array, 0, num2);
             num += num2;
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     zipOutputStream.Finish();
     zipOutputStream.Close();
     fileStream.Close();
 }
コード例 #8
0
        public byte[] diskLess()
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.WriteLine("HELLO!");
            sw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE WITHIN TWO FOLDERS");
            sw.Flush(); //This is required or you get a blank text file :)
            ms.Position = 0;

            // create the ZipEntry archive from the txt file in memory stream ms
            MemoryStream outputMS = new System.IO.MemoryStream();

            ZipOutputStream zipOutput = new ZipOutputStream(outputMS);

            ZipEntry ze = new ZipEntry(@"dir1/dir2/whatever.txt");
            zipOutput.PutNextEntry(ze);
            zipOutput.Write(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
            zipOutput.Finish();
            zipOutput.Close();
            byte[] byteArrayOut = outputMS.ToArray();
            outputMS.Close();

            ms.Close();

            return byteArrayOut;

        }
コード例 #9
0
ファイル: ZipHelper.cs プロジェクト: yonglehou/ToolRepository
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
        /// <param name="destinationZipFilePath">保存压缩文件的文件名</param>
        /// <param name="level">压缩文件等级</param>
        /// <returns>返回-2说明被压缩文件已经存在,返回1说明压缩成功</returns>            
        public static int CreateFileZip(string sourceFilePath, string destinationZipFilePath, int level)
        {
            if (!Directory.Exists(destinationZipFilePath.Substring(0, destinationZipFilePath.LastIndexOf("\\"))))
            {
                Directory.CreateDirectory(destinationZipFilePath.Substring(0, destinationZipFilePath.LastIndexOf("\\")));
            }
            if (File.Exists(destinationZipFilePath))
            {
                return -2;
            }
            else
            {
                ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
                zipStream.SetLevel(level);  // 压缩级别 0-9

                Crc32 crc = new Crc32();
                FileStream fileStream = File.OpenRead(sourceFilePath);
                byte[] buffer = new byte[fileStream.Length];
                fileStream.Read(buffer, 0, buffer.Length);
                string tempFile = sourceFilePath.Substring(sourceFilePath.LastIndexOf("\\") + 1);
                ZipEntry entry = new ZipEntry(tempFile);
                entry.DateTime = DateTime.Now;
                entry.Size = fileStream.Length;
                fileStream.Close();
                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                zipStream.PutNextEntry(entry);
                zipStream.Write(buffer, 0, buffer.Length);

                zipStream.Finish();
                zipStream.Close();
                return 1;
            }
        }
コード例 #10
0
ファイル: ZIPHelper.cs プロジェクト: fsoyka/RUOK
        public void Save(string extPath)
        {
            // https://forums.xamarin.com/discussion/7499/android-content-getexternalfilesdir-is-it-available
            Java.IO.File sd = Android.OS.Environment.ExternalStorageDirectory;
            //FileStream fsOut = File.Create(sd.AbsolutePath + "/Android/data/com.FSoft.are_u_ok_/files/MoodData.zip");
            FileStream fsOut = File.Create(extPath + "/MoodData.zip");
            //https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
            ZipOutputStream zipStream = new ZipOutputStream(fsOut);

            zipStream.SetLevel (3); //0-9, 9 being the highest level of compression
            zipStream.Password = "******";  // optional. Null is the same as not setting. Required if using AES.
            ZipEntry newEntry = new ZipEntry ("Mood.csv");
            newEntry.IsCrypted = true;
            zipStream.PutNextEntry (newEntry);
            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[ ] buffer = new byte[4096];
            string filename = extPath + "/MoodData.csv";
            using (FileStream streamReader = File.OpenRead(filename)) {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }

            zipStream.CloseEntry ();

            zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
            zipStream.Close ();
        }
コード例 #11
0
ファイル: ZipTask.cs プロジェクト: bbriggs/FieldWorks
		private void CompressFilesToOneZipFile(ICollection<string> inputPaths, string zipFilePath)
		{
			Log.LogMessage(MessageImportance.Normal, "Zipping " + inputPaths.Count + " files to zip file " + zipFilePath);

			using (var fsOut = File.Create(zipFilePath)) // Overwrites previous file
			{
				using (var zipStream = new ZipOutputStream(fsOut))
				{
					foreach (var inputPath in inputPaths)
					{
						zipStream.SetLevel(9); // Highest level of compression

						var inputFileInfo = new FileInfo(inputPath);

						var newEntry = new ZipEntry(inputFileInfo.Name) { DateTime = inputFileInfo.CreationTime };
						zipStream.PutNextEntry(newEntry);

						var buffer = new byte[4096];
						using (var streamReader = File.OpenRead(inputPath))
						{
							ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer);
						}

						zipStream.CloseEntry();
					}
					zipStream.IsStreamOwner = true;
					zipStream.Close();
				}
			}
		}
コード例 #12
0
ファイル: Util.cs プロジェクト: mabech/Projeto-Mestrado
        /// <summary>
        /// Método que faz o zip de arquivos encontrados no diretório <strPathDirectory>
        /// </summary>
        /// <param name="strPath"></param>
        public static void ZipFiles(String strPathDirectory, String strZipName)
        {
            try
            {
                using (ZipOutputStream ZipOut = new ZipOutputStream(File.Create(strPathDirectory + "\\" + strZipName + ".zip")))
                {
                    string[] OLfiles = Directory.GetFiles(strPathDirectory);
                    Console.WriteLine(OLfiles.Length);
                    ZipOut.SetLevel(9);
                    byte[] buffer = new byte[4096];

                    foreach (string filename in OLfiles)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(filename));
                        ZipOut.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(filename))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                ZipOut.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    ZipOut.Finish();
                    ZipOut.Close();
                }
            }
            catch (System.Exception ex)
            {
                System.Console.Error.WriteLine("exception: " + ex);
                //TODO colocar log
            }
        }
コード例 #13
0
ファイル: ZipArchiver.cs プロジェクト: limitzero/db-advance
        public void Zip(string outPathname, IList<ZipItem> contents)
        {
            var outputStream = File.Create(outPathname);
            var zipStream = new ZipOutputStream(outputStream);

            zipStream.SetLevel(3);

            foreach (var item in contents)
            {
                if (item.IsDirectory)
                {
                    var files = Directory.EnumerateFiles(item.FilePath);

                    foreach (var file in files)
                    {
                        AppendFile(zipStream, item.FolderInZip, file);
                    }
                }
                else
                {
                    AppendFile(zipStream, item.FolderInZip, item.FilePath);
                }
            }

            zipStream.IsStreamOwner = true;
            zipStream.Close();
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: TreeSeed/Tychaia
        public static void Main(string[] args)
        {
            var target = args[0];
            var filter = FileFilterParser.Parse(args[1], GetRecursiveFilesInCwd());

            using (var file = new FileStream(target, FileMode.Create))
            {
                using (var writer = new ZipOutputStream(file))
                {
                    foreach (var kv in filter)
                    {
                        var fi = new FileInfo(kv.Key);
                        var entry = new ZipEntry(kv.Value);
                        entry.DateTime = fi.LastWriteTime;
                        entry.Size = fi.Length;
                        writer.PutNextEntry(entry);
                        using (var streamReader = File.OpenRead(kv.Key))
                        {
                            streamReader.CopyTo(writer);
                        }

                        writer.CloseEntry();
                    }

                    writer.Close();
                }
            }
        }
コード例 #15
0
ファイル: ZipUtils.cs プロジェクト: jeasonyoung/csharp_sfit
 /// <summary>
 /// 将文件或目录压缩。
 /// </summary>
 /// <param name="paths">路径集合。</param>
 /// <returns>压缩后数据</returns>
 public static byte[] Zip(string[] paths)
 {
     byte[] data = null;
     if (paths != null && paths.Length > 0)
     {
         using (MemoryStream ms = new MemoryStream())
         {
             //压缩数据保存到临时文件。
             using (ZipOutputStream zipStream = new ZipOutputStream(ms))
             {
                 zipStream.SetLevel(9);
                 for (int i = 0; i < paths.Length; i++)
                 {
                     if (File.Exists(paths[i]))
                     {
                         ZipFileData(zipStream, paths[i], null, null);
                     }
                     else if (Directory.Exists(paths[i]))
                     {
                         ZipFolderData(zipStream, paths[i], string.Empty);
                     }
                 }
                 zipStream.IsStreamOwner = true;
                 zipStream.Close();
             }
             data = ms.ToArray();
         }
     }
     return data;
 }
コード例 #16
0
    public void Compress(System.IO.Stream OutputStream, System.IO.Stream InputStream)
    {
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream Compressor = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(OutputStream);
        Compressor.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("Entry"));

        byte[] buf = new byte[1024];
        int    n   = 0;

        while (true)
        {
            n = InputStream.Read(buf, 0, buf.Length);

            if (n == 0)
            {
                break;
            }
            else
            {
                Compressor.Write(buf, 0, n);
            }
        }

        Compressor.Flush();
        Compressor.Close();

        //delete(Compressor);
        //delete(buf);

        //OutputStream.Seek(0, System.IO.SeekOrigin.Begin);
    }
コード例 #17
0
        /// <summary>
        /// Создать архив
        /// </summary>
        /// <param name="InputFilePath">Входной файл</param>
        /// <param name="OutPutFilePath">Выходной архив с одним файлом</param>
        public static void CreateZip(string InputFilePath, string OutPutFilePath)
        {
            FileInfo outFileInfo = new FileInfo(OutPutFilePath);
            FileInfo inFileInfo  = new FileInfo(InputFilePath);

            // Create the output directory if it does not exist
            if (!Directory.Exists(outFileInfo.Directory.FullName))
            {
                Directory.CreateDirectory(outFileInfo.Directory.FullName);
            }

            // Compress
            using (FileStream fsOut = File.Create(OutPutFilePath))
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut))
                {
                    zipStream.UseZip64 = UseZip64.Off;
                    zipStream.SetLevel(9);

                    ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(inFileInfo.Name);
                    newEntry.DateTime = DateTime.UtcNow;
                    zipStream.PutNextEntry(newEntry);

                    byte[] buffer = new byte[4096];
                    using (FileStream streamReader = File.OpenRead(InputFilePath))
                    {
                        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer);
                    }

                    zipStream.CloseEntry();
                    zipStream.IsStreamOwner = true;
                    zipStream.Close();
                }
            }
        }
コード例 #18
0
    // Update is called once per frame
    //function Update ()
    //{
    //
    //}

    public void Compress(string OutputZipFileName, System.IO.Stream InputStream)
    {
        System.IO.FileStream raw = System.IO.File.Create(OutputZipFileName);
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream Compressor = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(raw);
        Compressor.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("Entry"));

        byte[] buf = new byte[1024];
        int    n   = 0;

        while (true)
        {
            n = InputStream.Read(buf, 0, buf.Length);

            if (n == 0)
            {
                break;
            }
            else
            {
                Compressor.Write(buf, 0, n);
            }
        }

        Compressor.Close();
        raw.Close();

        //delete(Compressor);
        //delete(buf);
    }
コード例 #19
0
ファイル: ZipCommand.cs プロジェクト: plkumar/jish
        public void zip(string to, string[] files)
        {
            using (ZipOutputStream s = new ZipOutputStream(File.Create(to)))
              {
            s.SetLevel(9);

            byte[] buffer = new byte[4096];

            foreach (string file in files)
            {
              ZipEntry entry = new ZipEntry(Path.GetFileName(file)) { DateTime = DateTime.Now };
              s.PutNextEntry(entry);

              using (FileStream fs = File.OpenRead(file))
              {
            int sourceBytes;
            do
            {
              sourceBytes = fs.Read(buffer, 0, buffer.Length);
              s.Write(buffer, 0, sourceBytes);
            } while (sourceBytes > 0);
              }
            }
            s.Finish();
            s.Close();
              }
        }
コード例 #20
0
        private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            ReportText = ReportTextBox.Text;
            ZipEntry ze;
            ZipOutputStream zip_out = new ZipOutputStream(File.Create((sender as SaveFileDialog).FileName));
            string SourceText;
            byte[] data=null;
            foreach (string FileName in FileNames)
            {
                SourceText = VEC.StandartCompiler.GetSourceFileText(FileName);
                if (SourceText != null)
                {
                    data = System.Text.Encoding.GetEncoding(1251).GetBytes(SourceText);
                    ze = new ZipEntry(System.IO.Path.GetFileName(FileName));
                    zip_out.PutNextEntry(ze);
                    zip_out.Write(data, 0, data.Length);
                }
            }
            ze = new ZipEntry("Report.txt");
            zip_out.PutNextEntry(ze);
            data = System.Text.Encoding.GetEncoding(1251).GetBytes(ReportText); 
            zip_out.Write(data, 0, data.Length);
           	zip_out.Finish();
			zip_out.Close();
        }
コード例 #21
0
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="sourcePath">待压缩的目录</param>
        /// <param name="zipFilePath">待生成的压缩文件</param>
        public static void CreateZipFile(string sourcePath, string zipFilePath)
        {
            if (!Directory.Exists(sourcePath) && !File.Exists(sourcePath))
                throw new IOException("找不到目录或文件sourcePath");

            if (!zipFilePath.ToLower().EndsWith(".zip"))
            {
                zipFilePath += ".zip";
            }

            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
            {
                s.SetLevel(9); // 压缩级别 0-9
                //s.Password = "******"; //Zip压缩文件密码

                if (Directory.Exists(sourcePath))
                    AppendZipDirectory(s, null, sourcePath);
                else if (File.Exists(sourcePath))
                    AppendZipFile(s, null, sourcePath);

                s.Finish();
                s.Close();

            }
        }
コード例 #22
0
    public void create_zip(string path, string filename, string type)
    {
        string fileNew;

        // Try
        fileNew = (filename + ".zip");
        //string f;
        string[] fname = Directory.GetFiles(path, type);
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipoutputstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create((path + fileNew)));
        zipoutputstream.SetLevel(6);
        ICSharpCode.SharpZipLib.Checksums.Crc32 objcrc32 = new ICSharpCode.SharpZipLib.Checksums.Crc32();
        foreach (string f in fname)
        {
            FileStream stream = File.OpenRead(f);
            byte[]     buff   = new byte[stream.Length];
            ICSharpCode.SharpZipLib.Zip.ZipEntry zipentry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(f.Substring((f.LastIndexOf("\\") + 1)));
            //stream.Read(buff, 0, buff.Length);
            stream.Read(buff, 0, buff.Length);
            zipentry.DateTime = DateTime.UtcNow.AddHours(5.5);
            zipentry.Size     = stream.Length;
            stream.Close();
            objcrc32.Reset();
            objcrc32.Update(buff);
            // zipentry.Crc = objcrc32.Value;
            zipoutputstream.PutNextEntry(zipentry);
            zipoutputstream.Write(buff, 0, buff.Length);
        }
        zipoutputstream.Flush();
        zipoutputstream.Finish();
        zipoutputstream.Close();
    }
コード例 #23
0
    private void Page_Load(object sender, System.EventArgs e)
    {
        System.DateTime dateTime = System.DateTime.Now;
        string          s1       = "Message_Backup_\uFFFD" + dateTime.ToString("ddMMyy_HHmmss\uFFFD") + ".zip\uFFFD";

        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(memoryStream);
        ActiveUp.Net.Mail.Mailbox mailbox = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(Request.QueryString["b\uFFFD"]);
        char[]   chArr = new char[] { ',' };
        string[] sArr  = Request.QueryString["m\uFFFD"].Split(chArr);
        for (int i = 0; i < sArr.Length; i++)
        {
            string s2   = sArr[i];
            byte[] bArr = mailbox.Fetch.Message(System.Convert.ToInt32(s2));
            ActiveUp.Net.Mail.Header             header   = ActiveUp.Net.Mail.Parser.ParseHeader(bArr);
            ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(header.Subject + ".eml\uFFFD");
            zipOutputStream.PutNextEntry(zipEntry);
            zipOutputStream.SetLevel(9);
            zipOutputStream.Write(bArr, 0, bArr.Length);
            zipOutputStream.CloseEntry();
        }
        zipOutputStream.Finish();
        Response.AddHeader("Content-Disposition\uFFFD", "attachment; filename=\uFFFD" + s1);
        Response.ContentType = "application/zip\uFFFD";
        Response.BinaryWrite(memoryStream.GetBuffer());
        zipOutputStream.Close();
    }
コード例 #24
0
        public FileResult DownloadAllFiles()
        {
            var context = System.Web.HttpContext.Current;
            var folderPath = context.Server.MapPath("~/UploadedFiles/");
            var baseOutputStream = new MemoryStream();
            ZipOutputStream zipOutput = new ZipOutputStream(baseOutputStream) {IsStreamOwner = false};

            /*
            * Higher compression level will cause higher usage of reources
            * If not necessary do not use highest level 9
            */

            zipOutput.SetLevel(4);
            SharpZipLibHelper.ZipFolder(folderPath, zipOutput);

            zipOutput.Finish();
            zipOutput.Close();

            /* Set position to 0 so that cient start reading of the stream from the begining */
            baseOutputStream.Position = 0;

            /* Set custom headers to force browser to download the file instad of trying to open it */
            return new FileStreamResult(baseOutputStream, "application/x-zip-compressed")
            {
                FileDownloadName = "eResult.zip"
            };
        }
コード例 #25
0
 private void Page_Load(object sender, System.EventArgs e)
 {
     System.DateTime dateTime = System.DateTime.Now;
     string s1 = "Message_Backup_\uFFFD" + dateTime.ToString("ddMMyy_HHmmss\uFFFD") + ".zip\uFFFD";
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(memoryStream);
     ActiveUp.Net.Mail.Mailbox mailbox = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(Request.QueryString["b\uFFFD"]);
     char[] chArr = new char[] { ',' };
     string[] sArr = Request.QueryString["m\uFFFD"].Split(chArr);
     for (int i = 0; i < sArr.Length; i++)
     {
         string s2 = sArr[i];
         byte[] bArr = mailbox.Fetch.Message(System.Convert.ToInt32(s2));
         ActiveUp.Net.Mail.Header header = ActiveUp.Net.Mail.Parser.ParseHeader(bArr);
         ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(header.Subject + ".eml\uFFFD");
         zipOutputStream.PutNextEntry(zipEntry);
         zipOutputStream.SetLevel(9);
         zipOutputStream.Write(bArr, 0, bArr.Length);
         zipOutputStream.CloseEntry();
     }
     zipOutputStream.Finish();
     Response.AddHeader("Content-Disposition\uFFFD", "attachment; filename=\uFFFD" + s1);
     Response.ContentType = "application/zip\uFFFD";
     Response.BinaryWrite(memoryStream.GetBuffer());
     zipOutputStream.Close();
 }
コード例 #26
0
        public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
        {
            ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
            int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
            // find number of chars to remove 	// from orginal file path
            TrimLength += 1; //remove '\'
            FileStream ostream;
            byte[] obuffer;
            string outPath = outputPathAndFile;
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
            if (password != null && password != String.Empty)
                oZipStream.Password = password;
            oZipStream.SetLevel(9); // maximum compression
            ZipEntry oZipEntry;
            foreach (string Fil in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);

                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(Fil);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }
            }
            oZipStream.Finish();
            oZipStream.Close();
            oZipStream.Dispose();
        }
コード例 #27
0
ファイル: ZipCompressor.cs プロジェクト: tgiphil/wintools
        public void CreateZipFile(string[] straFilenames, string strOutputFilename)
        {
            Crc32 crc = new Crc32();
            ZipOutputStream zos = new ZipOutputStream(File.Create(strOutputFilename));

            zos.SetLevel(m_nCompressionLevel);

            foreach (string strFileName in straFilenames)
            {
                FileStream fs = File.OpenRead(strFileName);

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                ZipEntry entry = new ZipEntry(GetFileNameWithoutDrive(strFileName));

                entry.DateTime = DateTime.Now;

                entry.Size = fs.Length;
                fs.Close();

                crc.Reset();
                crc.Update(buffer);

                entry.Crc  = crc.Value;

                zos.PutNextEntry(entry);

                zos.Write(buffer, 0, buffer.Length);
            }

            zos.Finish();
            zos.Close();
        }
コード例 #28
0
        private static void CreateToMemoryStream(IEnumerable<Tuple<string, Stream>> entries, string zipName)
        {
            MemoryStream outputMemStream = new MemoryStream();
            ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

            zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

            foreach (var entry in entries)
            {
                ZipEntry newEntry = new ZipEntry(entry.Item1);
                newEntry.DateTime = DateTime.Now;

                zipStream.PutNextEntry(newEntry);

                StreamUtils.Copy(entry.Item2, zipStream, new byte[4096]);
                zipStream.CloseEntry();
            }

            zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
            zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.

            outputMemStream.Position = 0;
            File.WriteAllBytes(zipName, outputMemStream.ToArray());

            //// Alternative outputs:
            //// ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.
            //byte[] byteArrayOut = outputMemStream.ToArray();

            //// GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
            //byte[] byteArrayOut = outputMemStream.GetBuffer();
            //long len = outputMemStream.Length;
        }
コード例 #29
0
        public static void CreateFromDirectory(string[] sourceFileNames, string destinationArchiveFileName)
        {
            using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationArchiveFileName))) 
            {
                byte[] buffer = new byte[BufferSize];
                
                zipStream.SetLevel(9); 
             
                foreach (string file in sourceFileNames)
                {
                    var entryName = Path.GetFileName(file);
                    var fileInfo = new FileInfo(file);

                    ZipEntry entry = new ZipEntry(entryName);
                    entry.DateTime = fileInfo.LastWriteTime;
                    zipStream.PutNextEntry(entry);
                    
                    using (FileStream fileStream = File.OpenRead(file)) 
                    {
                        while (true)
                        {
                            int size = fileStream.Read(buffer, 0, buffer.Length);
                            if (size <= 0) 
                                break;
                            
                            zipStream.Write(buffer, 0, size);
                        }
                    }
                }
                
                zipStream.Finish();
                zipStream.Close();
            }
        }
コード例 #30
0
ファイル: ZipOperation.cs プロジェクト: ronanb67/timeflies
        public static void CreateZipFile(string[] filenames, string outputFile)
        {
            // Zip up the files - From SharpZipLib Demo Code
              using (ZipOutputStream s = new ZipOutputStream(File.Create(outputFile)))
              {
            s.SetLevel(9); // 0-9, 9 being the highest level of compression
            byte[] buffer = new byte[4096];
            foreach (string file in filenames)
            {
              ZipEntry entry = new ZipEntry(Path.GetFileName(file));
              entry.DateTime = DateTime.Now;
              s.PutNextEntry(entry);

              using (FileStream fs = File.OpenRead(file))
              {
            int sourceBytes;
            do
            {
              sourceBytes = fs.Read(buffer, 0, buffer.Length);
              s.Write(buffer, 0, sourceBytes);

            }
            while (sourceBytes > 0);
              }
            }
            s.Finish();
            s.Close();
              }
        }
コード例 #31
0
ファイル: ZipFile.cs プロジェクト: BlueSky007/Demo55
        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
        {
            //如果文件没有找到,则报错
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
            }

            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipEntry ZipEntry = new ZipEntry("ZippedFile");
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[BlockSize];
            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
            ZipStream.Write(buffer, 0, size);
            try
            {
                while (size < StreamToZip.Length)
                {
                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                    ZipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            ZipStream.Finish();
            ZipStream.Close();
            StreamToZip.Close();
        }
コード例 #32
0
ファイル: ZipUtili.cs プロジェクト: sinaaslani/kids.bmi.ir
        public static void ZipFile(IEnumerable<string> InputFilePath, string outputPathAndFile, string password)
        {
            string outPath = outputPathAndFile;
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath));

            foreach (string FilePath in InputFilePath)
            {
                int TrimLength = 0;
                if (Path.GetDirectoryName(FilePath) != null)
                {
                    TrimLength = (Path.GetDirectoryName(FilePath)).Length;
                    TrimLength += 1; //remove '\'
                }


                if (!string.IsNullOrEmpty(password))
                    oZipStream.Password = password;
                oZipStream.SetLevel(9); // maximum compression

                ZipFile(TrimLength, oZipStream, FilePath);
            }
            

            oZipStream.Finish();
            oZipStream.Close();
        }
コード例 #33
0
        // See this link for details on zipping using SharpZipLib:  https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#wiki-anchorCreate
        public void Write(Cookbookology.Domain.Cookbook cookbook, Stream outputStream)
        {
            if (cookbook == null) throw new ArgumentNullException("cookbook");
            if (outputStream == null) throw new ArgumentNullException("outputStream");

            var converter = new MyCookbookConverter();
            var mcb = converter.ConvertFromCommon(cookbook);

            var ms = new MemoryStream();
            var s = new XmlSerializer(typeof(Cookbook));
            s.Serialize(ms, mcb);
            ms.Position = 0; // reset to the start so that we can write the stream

            // Add the cookbook as a single compressed file in a Zip
            using (var zipStream = new ZipOutputStream(outputStream))
            {
                zipStream.SetLevel(3); // compression
                zipStream.UseZip64 = UseZip64.Off; // not compatible with all utilities and OS (WinXp, WinZip8, Java, etc.)

                var entry = new ZipEntry(mcbFileName);
                entry.DateTime = DateTime.Now;

                zipStream.PutNextEntry(entry);
                StreamUtils.Copy(ms, zipStream, new byte[4096]);
                zipStream.CloseEntry();

                zipStream.IsStreamOwner = false; // Don't close the outputStream (parameter)
                zipStream.Close();
            }
        }
コード例 #34
0
ファイル: FileHelper.cs プロジェクト: VilsonLu/msthesis-som
        public void CompressFile(string sourcePath, string destinationPath)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(destinationPath)))
            {
                zipStream.SetLevel(9);

                byte[] buffer = new byte[4096];
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(sourcePath));

                entry.DateTime = DateTime.Now;
                zipStream.PutNextEntry(entry);

                using (FileStream fs = File.OpenRead(sourcePath))
                {
                    int sourceBytes = 0;
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }

                zipStream.Finish();
                zipStream.Close();
                zipStream.Dispose();
            }
        }
コード例 #35
0
        /// <summary>
        /// Zips the files in the specifed directory and outputs the zip file to the specified location.
        /// </summary>
        /// <param name="zipFilePath">The full path to the output zip file.</param>
        /// <returns>The total number of files added to the zip file.</returns>
        public int ZipToFile(string zipFilePath)
        {
            int total = 0;

            if (Directory.Exists(DirectoryPath))
            {
                if (!Directory.Exists(Path.GetDirectoryName(zipFilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath));
                }

                // Create the zip file
                //Crc32 crc = new Crc32();
                ZipOutputStream zipFile = new ZipOutputStream(File.Create(zipFilePath));
                zipFile.UseZip64 = UseZip64.Off;
                zipFile.SetLevel(9);

                total += ZipFromPath(zipFile, DirectoryPath);

                // Close the writer
                zipFile.Finish();
                zipFile.Close();
            }

            return total;
        }
コード例 #36
0
ファイル: FileEx.cs プロジェクト: Venbb/mgame
		/// <summary>
		/// 压缩文件
		/// </summary>
		/// <param name="strFile">压缩源路径</param>
		/// <param name="strZip">压缩文件保存路径</param>
		/// <param name = "rootDir">压缩文件根目录</param>
		/// <param name = "isEndExtent">是否压缩包含扩展名的文件</param>
		/// <param name = "extents">用于筛选的扩展名</param>
		public static void ZipFile (string strFile, string strZip, string rootDir = "", bool isEndExtent = false, params string[] extents)
		{
			var s = new ZipOutputStream (File.Create (strZip));
			s.SetLevel (9); // 0 - store only to 9 - means best compression
			zip (strFile, s, rootDir, isEndExtent, extents);
			s.Finish ();
			s.Close ();
		}
コード例 #37
0
        public static string CreateZIPFile(string path, int M, string strsuff)
        {
            try
            {
                Crc32 crc = new Crc32();//未压缩的
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipout = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(path + ".zip"));

                //ICSharpCode.SharpZipLib.GZip.GZipOutputStream zipout = new GZipOutputStream(System.IO.File.Create(path+ ".zip"));
                System.IO.FileStream fs = System.IO.File.OpenRead(path + strsuff);
                long   pai    = 1024 * 1024 * M;//每M兆写一次
                long   forint = fs.Length / pai + 1;
                byte[] buffer = null;
                zipout.SetLevel(7);
                ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(path + strsuff));
                entry.Size     = fs.Length;
                entry.DateTime = DateTime.Now;
                zipout.PutNextEntry(entry);
                //zipout.
                for (long i = 1; i <= forint; i++)
                {
                    if (pai * i < fs.Length)
                    {
                        buffer = new byte[pai];
                        fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
                    }
                    else
                    {
                        if (fs.Length < pai)
                        {
                            buffer = new byte[fs.Length];
                        }
                        else
                        {
                            buffer = new byte[fs.Length - pai * (i - 1)];
                            fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
                        }
                    }
                    fs.Read(buffer, 0, buffer.Length);
                    crc.Reset();
                    crc.Update(buffer);
                    zipout.Write(buffer, 0, buffer.Length);
                    zipout.Flush();
                }
                fs.Close();
                zipout.Finish();
                zipout.Close();

                System.IO.File.Delete(path + strsuff);
                // File.Create(path.Replace(".doc","") + ".zip",buffer.Length);
                return(path + ".zip");
            }
            catch (Exception ex)
            {
                string str = ex.Message;
                return(path);
            }
        }
コード例 #38
0
    static public void Compression(string ZipPath, string Root, List <string> zipSrcList)
    {
        try
        {
            string zipPath = ZipPath + ".zip";

            System.IO.FileStream writer = new System.IO.FileStream(zipPath,
                                                                   System.IO.FileMode.Create,
                                                                   System.IO.FileAccess.Write, System.IO.FileShare.Write);

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos =
                new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer);

            string file = "";
            int    cnt  = zipSrcList.Count;
            for (int i = 0; i < cnt; ++i)
            {
                if (Root != null)
                {
                    file = string.Format("{0}/{1}", Root, zipSrcList[i]);
                }
                else
                {
                    file = zipSrcList[i];
                }

                ICSharpCode.SharpZipLib.Zip.ZipEntry ze =
                    new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipSrcList[i]);

                System.IO.FileStream fs = new System.IO.FileStream(file,
                                                                   System.IO.FileMode.Open, System.IO.FileAccess.Read,
                                                                   System.IO.FileShare.Read);

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                ze.Size = buffer.Length;

                ze.DateTime = DateTime.Now;

                // 새로운 엔트리(파일)을 넣는다.
                zos.PutNextEntry(ze);

                // 쓰기
                zos.Write(buffer, 0, buffer.Length);
            }
            zos.Close();
            writer.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError("Zip Error : " + ex.ToString());
        }
    }
コード例 #39
0
 /// <summary>
 /// 压缩文件(Zip)
 /// </summary>
 /// <param name="filesPath">待压缩文件目录</param>
 /// <param name="zipFilePath">压缩文件输出目录</param>
 /// <returns></returns>
 public static ZipInfo CreateZipFile(string filesPath, string zipFilePath)
 {
     if (!System.IO.Directory.Exists(filesPath))
     {
         return(new ZipInfo
         {
             Success = false,
             InfoMessage = "没有找到文件"
         });
     }
     try
     {
         string[] filenames = System.IO.Directory.GetFiles(filesPath);
         using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath)))
         {
             s.SetLevel(9);                  // 压缩级别 0-9
             //s.Password = "******"; //Zip压缩文件密码
             byte[] buffer = new byte[4096]; //缓冲区大小
             foreach (string file in filenames)
             {
                 ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(file));
                 entry.DateTime = DateTime.Now;
                 s.PutNextEntry(entry);
                 using (FileStream fs = File.OpenRead(file))
                 {
                     int sourceBytes;
                     do
                     {
                         sourceBytes = fs.Read(buffer, 0, buffer.Length);
                         s.Write(buffer, 0, sourceBytes);
                     } while (sourceBytes > 0);
                 }
             }
             s.Finish();
             s.Close();
         }
         return(new ZipInfo
         {
             Success = true,
             InfoMessage = "压缩成功"
         });
     }
     catch (Exception ex)
     {
         return(new ZipInfo
         {
             Success = false,
             InfoMessage = ex.Message
         });
     }
 }
コード例 #40
0
        public static Boolean ZipFile(String filePath, String zipFile)
        {
            if (!File.Exists(filePath))
            {
                Debug.WriteLine("Cannot find file '{0}'", filePath);
                return(false);
            }

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFile)))
                {
                    zipStream.SetLevel(9);         //0~9

                    byte[] buffer = new byte[4096];
                    ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(filePath));

                    entry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(entry);

                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        int sourceBytes = 0;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }

                    zipStream.Finish();
                    zipStream.Close();
                    zipStream.Dispose();
                }

                if (File.Exists(zipFile))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception during processing {0}", ex);
            }
            return(false);
        }
コード例 #41
0
 private String CompressionDossier(String pFichier)
 {
     try
     {
         if (Directory.Exists(pFichier) == true)
         {
             //System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream();
             using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(String.Format("{0}.zip", pFichier))))
             {
                 s.SetLevel(9);
                 var buffer = new byte[4096];
                 var entry  = new ICSharpCode.SharpZipLib.Zip.ZipEntry(pFichier)
                 {
                     DateTime = DateTime.Now
                 };
                 s.PutNextEntry(entry);
                 using (StreamReader fs = new StreamReader(pFichier))
                 {
                     int sourceBytes;
                     do
                     {
                         sourceBytes = fs.Read();
                         s.Write(buffer, 0, sourceBytes);
                     } while (sourceBytes > 0);
                 }
                 s.Finish();
                 s.Close();
                 s.Dispose();
                 pFichier = string.Format("{0}.zip", pFichier);
             }
             //}
         }
         return(pFichier);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #42
0
        public async Task <Stream> CompressFile(Dictionary <string, Stream> fileDic, string password)
        {
            var result    = new MemoryStream();
            var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(result);

            zipStream.Password = string.Empty;
            zipStream.SetLevel(9); //0-9, 9 being the highest level of compression
            foreach (var data in fileDic)
            {
                var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(data.Key)
                {
                    DateTime      = DateTime.Now,
                    IsUnicodeText = true
                };
                zipStream.PutNextEntry(newEntry);
                var length = data.Value.Length < 1024 ? 1024 : data.Value.Length;
                ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(data.Value, zipStream, new byte[length]);
                zipStream.CloseEntry();
                zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
            }
            zipStream.Close();                   // Must finish the ZipOutputStream before using outputMemStream.
            result.Position = 0;
            return(result);
        }
コード例 #43
0
    protected void btnExport_Click(object sender, EventArgs e)
    {
        string xType = ddlExportType.SelectedItem.Text;
        bool   xPack = ckbExportMulti.Checked;

        if (xPack)
        {
            Master.Log.Info("Creating package: " + txtZipName.Text);
            if (txtZipName.Text == "")
            {
                lblFNError.Visible = true;
                return;
            }
            else
            {
                lblFNError.Visible = false;
            }

            using (MemoryStream OutputStream = new MemoryStream())
            {
                // Setup Zip Stream
                string zipFileName = txtZipName.Text + ".osapkg";
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(OutputStream);
                zipStream.SetLevel(3);
                zipStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.On;
                // Add each object on list to Zip in reverse order.
                int lstCount = lstFileList.Items.Count;
                if (lstCount > 0)
                {
                    //foreach (ListItem lstItem in lstFileList.Items)
                    while (lstCount > 0)
                    {
                        ListItem lstItem = lstFileList.Items[lstCount - 1];
                        int      iSplit  = lstItem.Text.IndexOf("::");
                        string[] args    = new string[2]; //lstItem.Text.Split(':',':');
                        args[0] = lstItem.Text.Substring(0, iSplit);
                        args[1] = lstItem.Text.Substring(iSplit + 2);
                        ExportObject xObj = new ExportObject(args[0], args[1]);
                        Master.Log.Info("Adding file: " + xObj.ExportFileName + " to package: " + txtZipName.Text);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(xObj.ExportFileName);
                        zipEntry.DateTime = DateTime.Now;
                        zipEntry.Size     = xObj.byteData.Length;
                        zipStream.PutNextEntry(zipEntry);
                        zipStream.Write(xObj.byteData, 0, xObj.byteData.Length);
                        zipStream.Flush();
                        zipStream.CloseEntry();
                        lstCount = lstCount - 1;
                    }
                }

                // Finish up Zip
                zipStream.IsStreamOwner = false;
                zipStream.Close();
                OutputStream.Position = 0;
                byte[] byteArray = OutputStream.GetBuffer();
                Int64  leng      = byteArray.Length;
                Response.Clear();
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + zipFileName);
                Response.AppendHeader("Content-Length", leng.ToString());
                Response.ContentType = "application/zip";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Master.Log.Info("Exported package: " + txtZipName.Text + " - By User: "******"Username"]);
            }
        }
        else
        {
            // Only 1 File
            lstFileList.Items.Clear();
            ExportObject sExport = new ExportObject(ddlObjToExport.SelectedValue, ddlExportType.SelectedValue);
            Master.Log.Info("Exporting File: " + sExport.ExportFileName + " - By User: "******"Username"]);
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=\"" + sExport.ExportFileName + "\"");
            Response.Charset = "";
            if (sExport.DataType == "Text")
            {
                Response.ContentType = "application/text";
                StringBuilder sb = new StringBuilder(sExport.stringData);
                Response.Output.Write(sb.ToString());
            }
            else if (sExport.Type == "Image")
            {
                Response.ContentType = "image/" + Path.GetExtension(sExport.ExportFileName);
                Response.BinaryWrite(sExport.byteData);
            }
            else
            {
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Length", sExport.ByteSize.ToString());
                Response.BinaryWrite(sExport.byteData);
            }
            Response.Flush();
            Response.End();
            //Master.Log.Info("Exported file: " + sExport.ExportFileName + " - By User: "******"Username"]);
        }
        btnClear_Click(this, null);
    }
コード例 #44
0
        }                 // Unpack

        /// <summary>
        /// Zip a file.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="appendZipExtension"></param>
        public static void PackFile(string filename, bool appendZipExtension)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }
            if (!File.Exists(filename))
            {
                throw new ArgumentException(string.Format("File does not exist: {0}.", filename), "filename");
            }

            string newFilename = filename + ".zip";

            if (!appendZipExtension)
            {
                newFilename = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".zip";
            }
            if (File.Exists(newFilename))
            {
                File.Delete(newFilename);
            }

            FileStream fileStreamOut = File.Create(newFilename);

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fileStreamOut);
            zipOutputStream.SetLevel(9);

            ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filename));
            zipOutputStream.PutNextEntry(zipEntry);

            FileStream fileStreamIn = File.OpenRead(filename);
            const long BUFFER_SIZE  = 8192;
            long       currentIndex = 0;

            byte[] buffer = new byte[BUFFER_SIZE];
            if (fileStreamIn.Length <= BUFFER_SIZE)
            {
                fileStreamIn.Read(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
                zipOutputStream.Write(buffer, 0, Convert.ToInt32(fileStreamIn.Length));
            }
            else
            {
                do
                {
                    long remaining = BUFFER_SIZE;
                    if (currentIndex + BUFFER_SIZE >= fileStreamIn.Length)
                    {
                        remaining = fileStreamIn.Length - currentIndex;
                    }
                    fileStreamIn.Read(buffer, 0, Convert.ToInt32(remaining));
                    currentIndex += remaining;

                    zipOutputStream.Write(buffer, 0, Convert.ToInt32(remaining));
                } while (currentIndex < fileStreamIn.Length);
            }
            fileStreamIn.Close();

            zipOutputStream.Flush();
            zipOutputStream.Finish();
            zipOutputStream.Close();

            fileStreamOut.Close();
        }// ZipFile