This class represents an entry in a zip archive. This can be a file or a directory ZipFile and ZipInputStream will give you instances of this class as information about the members in an archive. ZipOutputStream uses an instance of this class when creating an entry in a Zip file.

Author of the original java version : Jochen Hoenicke
示例#1
0
 private void zip(string strFile, ZipOutputStream s, string staticFile)
 {
     if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
     Crc32 crc = new Crc32();
     string[] filenames = Directory.GetFileSystemEntries(strFile);
     foreach (string file in filenames)
     {
         if (Directory.Exists(file))
         {
             zip(file, s, staticFile);
         }
         else // 否则直接压缩文件
         {
             //打开压缩文件
             FileStream fs = File.OpenRead(file);
             byte[] buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
             ZipEntry entry = new ZipEntry(tempfile);
             entry.DateTime = DateTime.Now;
             entry.Size = fs.Length;
             fs.Close();
             crc.Reset();
             crc.Update(buffer);
             entry.Crc = crc.Value;
             s.PutNextEntry(entry);
             s.Write(buffer, 0, buffer.Length);
         }
     }
 }
示例#2
0
        public static string PackToBase64(string text)
        {
            byte[]       buffer;
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                zipOutputStream.SetLevel(9);


                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin");
                zipOutputStream.PutNextEntry(zipEntry);

                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(text.ToCharArray());

                zipOutputStream.Write(bytes, 0, bytes.Length);

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

                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
            }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ...

            return(ToBase64(buffer));
        }
示例#3
0
 internal virtual Stream GetInputStream(ZLib.ZipEntry zipEntry)
 {
     lock (this)
     {
         return(new PrivateStreamWrapper(this.zipFile.GetInputStream(zipEntry)));
     }
 }
示例#4
0
        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();
        }
示例#5
0
 public Stream GetInputStream(ZipEntry entry)
 {
     if (zipArchive == null)
         throw new InvalidDataException("Zip File is closed");
     Stream s = zipArchive.GetInputStream(entry);
     return s;
 }
示例#6
0
		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();
				}
			}
		}
示例#7
0
        /// <summary>
        /// Compress an string using ZIP
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static byte[] CompressContent(string contentToZip)
        {

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] buff = encoding.GetBytes(contentToZip);

            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    using (ZipOutputStream zipout = new ZipOutputStream(stream))
                    {
                        zipout.SetLevel(9);
                        ZipEntry entry = new ZipEntry("zipfile.zip");
                        entry.DateTime = DateTime.Now;
                        zipout.PutNextEntry(entry);
                        zipout.Write(buff, 0, buff.Length);
                        zipout.Finish();
                        byte[] outputbyte = new byte[(int)stream.Length];
                        stream.Position = 0;
                        stream.Read(outputbyte, 0, (int)stream.Length);
                        return outputbyte;
                    }

                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }
        }
	public override bool Marshall(PackagePart part, Stream out1)
	{
		if (!(out1 is ZipOutputStream)) {
			throw new ArgumentException("ZipOutputStream expected!");
		}
		ZipOutputStream zos = (ZipOutputStream) out1;

		// Saving the part in the zip file
		string name = ZipHelper
				.GetZipItemNameFromOPCName(part.PartName.URI.ToString());
        ZipEntry ctEntry = new ZipEntry(name);

        try
        {
            // Save in ZIP
            zos.PutNextEntry(ctEntry); // Add entry in ZIP

            base.Marshall(part, out1); // Marshall the properties inside a XML
            // Document
            StreamHelper.SaveXmlInStream(xmlDoc, out1);

            zos.CloseEntry();
        }
        catch (IOException e)
        {
            throw new OpenXml4NetException(e.Message);
        }
        catch
        {
            return false; 
        }
		return true;
	}
示例#9
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 ();
        }
        public override void ExecuteResult(ControllerContext context)
        {
            string fileName = Path.GetTempFileName();

            var response = context.HttpContext.Response;

            using (var zipOutputStream = new ZipOutputStream(new FileStream(fileName, FileMode.OpenOrCreate)))
            {
                zipOutputStream.SetLevel(0);
                foreach (var photo in Photos)
                {
                    //FileInfo fileInfo = new FileInfo(photo.MediaFilePath);
                    ZipEntry entry = new ZipEntry(Tag.Name + @"\" + photo.Id + ".jpg");
                    zipOutputStream.PutNextEntry(entry);
                    using (FileStream fs = System.IO.File.OpenRead(photo.MediaFilePath))
                    {

                        byte[] buff = new byte[1024];
                        int n = 0;
                        while ((n = fs.Read(buff, 0, buff.Length)) > 0)
                            zipOutputStream.Write(buff, 0, n);
                    }
                }
                zipOutputStream.Finish();
            }

            System.IO.FileInfo file = new System.IO.FileInfo(fileName);
            response.Clear();
            response.AddHeader("Content-Disposition", "attachment; filename=" + "Photos.zip");
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/octet-stream";
            response.WriteFile(file.FullName);
            response.End();
            System.IO.File.Delete(fileName);
        }
示例#11
0
        public void PackageFiles(IEnumerable<ZipFileEntry> filesToZip)
        {
            using (var zipStream = new ZipOutputStream(File.Create(ZipFilePath)))
            {
                if (!string.IsNullOrEmpty(Password))
                {
                    zipStream.Password = Password;
                }

                zipStream.SetLevel(9); // 9 -> "highest compression"

                foreach (var fileEntry in filesToZip)
                {
                    var zipEntry = new ZipEntry(fileEntry.FilePathInsideZip);
                    var fileInfo = new FileInfo(fileEntry.AbsoluteFilePath);
                    zipEntry.DateTime = fileInfo.LastWriteTime;
                    zipEntry.Size = fileInfo.Length;

                    zipStream.PutNextEntry(zipEntry);

                    // Zip the file in buffered chunks
                    var buffer = new byte[4096];
                    using (var streamReader = File.OpenRead(fileEntry.AbsoluteFilePath))
                    {
                        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer);
                    }

                    zipStream.CloseEntry();
                }

                zipStream.Finish();
                zipStream.Close();
            }
        }
示例#12
0
   /// <summary>
 /// 压缩文件夹
 /// </summary>
 /// <param name="dirToZip"></param>
 /// <param name="zipedFileName"></param>
 /// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param>
 public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9)
 {
     if (Path.GetExtension(zipedFileName) != ".zip")
     {
         zipedFileName = zipedFileName + ".zip";
     }
     using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName)))
     {
         zipoutputstream.SetLevel(compressionLevel);
         var crc = new Crc32();
         var fileList = GetAllFies(dirToZip);
         foreach (DictionaryEntry item in fileList)
         {
             var fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
             var buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             // ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
             var entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
                              {
                                  DateTime = (DateTime) item.Value,
                                  Size = fs.Length
                              };
             fs.Close();
             crc.Reset();
             crc.Update(buffer);
             entry.Crc = crc.Value;
             zipoutputstream.PutNextEntry(entry);
             zipoutputstream.Write(buffer, 0, buffer.Length);
         }
     }
 }
示例#13
0
    private void ParseZipAsync(byte[] zipFileData, Action <byte[]> callback)
    {
        Loom.RunAsync(() =>
        {
            MemoryStream stream = new MemoryStream(zipFileData);
            stream.Seek(0, SeekOrigin.Begin);
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(stream);

            for (ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry = zipStream.GetNextEntry(); theEntry != null; theEntry = zipStream.GetNextEntry())
            {
                if (theEntry.IsFile == false)
                {
                    continue;
                }

                if (theEntry.Name.EndsWith(".meta"))
                {
                    continue;
                }

                string fileName = Path.GetFileName(theEntry.Name);
                if (fileName != String.Empty)
                {
                    List <byte> result = new List <byte>();
                    byte[] data        = new byte[2048];
                    while (true)
                    {
                        int size = zipStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            var bytes = new Byte[size];
                            Array.Copy(data, bytes, size);
                            result.AddRange(bytes);
                        }
                        else
                        {
                            break;
                        }
                    }

                    //文件名都转为小写
                    if (m_DictLuaScriptData.ContainsKey(fileName.ToLower()))
                    {
                        string str = string.Format("ResourcesManager.InitZip:Zip中文件名{0}重复", fileName);
                        Debug.LogError(str);
                        continue;
                    }
                    m_DictLuaScriptData.Add(theEntry.Name.ToLower(), result.ToArray());
                }
            }

            zipStream.Close();
            stream.Close();

            Loom.QueueOnMainThread(() =>
            {
                callback(zipFileData);
            });
        });
    }
        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;

        }
示例#15
0
        /// <summary>
        /// 递归压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
        /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
        /// <param name="staticFile"></param>
        private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
        {
            Crc32 crc = new Crc32();
            string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
            foreach (string file in filesArray)
            {
                if (Directory.Exists(file))                     //如果当前是文件夹,递归
                {
                    CreateZipFiles(file, zipStream, staticFile);
                }

                else                                            //如果是文件,开始压缩
                {
                    FileStream fileStream = File.OpenRead(file);

                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    string tempFile = file.Substring(staticFile.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);
                }
            }
        }
示例#16
0
        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();
            }
        }
        // Recurses down the folder structure
        //
        private void CompressFile(string filename, ZipOutputStream zipStream, int fileOffset)
        {
            var fi = new FileInfo(filename);

            var entryName = Path.GetFileName(filename); // Makes the name in zip based on the folder
            entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
            var newEntry = new ZipEntry(entryName);
            newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity

            // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
            //   newEntry.AESKeySize = 256;

            // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
            // you need to do one of the following: Specify UseZip64.Off, or set the Size.
            // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
            // but the zip will be in Zip64 format which not all utilities can understand.
            //   zipStream.UseZip64 = UseZip64.Off;
            newEntry.Size = fi.Length;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            var buffer = new byte[4096];
            using (var streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();
        }
示例#18
0
        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();
        }
        // 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();
            }
        }
示例#20
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();
    }
示例#21
0
 public void Decompress(ZipEntry file, Stream str) {
   int size;
   while (true) {
     size = zipIn.Read(buf, 0, buf.Length); if (size <= 0) break;
     str.Write(buf, 0, (int)size);
   }
 }
示例#22
0
        /// <summary>
        /// ファイルを圧縮
        /// </summary>
        /// <param name="filename">ファイル名フルパス</param>
        /// <param name="offsetFolderName">圧縮時のルートフォルダのフルパス</param>
        /// <param name="zipStream">圧縮先のZipStream</param>
        public static void CompressFile(string filename, string offsetFolderName, ZipOutputStream zipStream)
        {
            //フォルダのオフセット値を取得
            var folderOffset = offsetFolderName.Length + (offsetFolderName.EndsWith("\\") ? 0 : 1);

            //ファイル名の余計なパスを消す
            string entryName = filename.Substring(folderOffset);
            entryName = ZipEntry.CleanName(entryName);

            //圧縮するファイルを表示←非常に良くない
            Console.WriteLine(entryName);

            //ファイル情報書き込み
            var fi = new FileInfo(filename);
            var newEntry = new ZipEntry(entryName)
            {
                DateTime = fi.LastWriteTime,
                Size = fi.Length,
            };
            zipStream.PutNextEntry(newEntry);

            //ファイル内容書き込み
            var buffer = new byte[4096];
            using (var streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }

            zipStream.CloseEntry();
        }
示例#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 static string PackToBase64(byte[] data)
        {
            byte[]       buffer;
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                zipOutputStream.SetLevel(9);


                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Boliglag.Admin");
                zipOutputStream.PutNextEntry(zipEntry);

                zipOutputStream.Write(data, 0, data.Length);

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

                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
            }//using ( ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream( fileStreamOut ) ) ...

            return(ToBase64(buffer));
        }
示例#25
0
 public ClsZipFileItem(string zipPath, ZipEntry entry)
     : base(entry.Name, entry.DateTime)
 {
     _path = entry.Name;
     _entry = entry;
     _zipPath = zipPath;
 }
示例#26
0
文件: Program.cs 项目: rxtur/BeDeploy
        private static void CompressFolder(string path, ZipOutputStream zipStream)
        {
            string[] files = Directory.GetFiles(path);
            foreach (string filename in files)
            {
                FileInfo fi = new FileInfo(filename);

                int offset = _root.Length + 3;
                string entryName = filename.Substring(offset);
                entryName = ZipEntry.CleanName(entryName);
                ZipEntry newEntry = new ZipEntry(entryName);
                newEntry.DateTime = fi.LastWriteTime;

                newEntry.Size = fi.Length;
                zipStream.PutNextEntry(newEntry);

                byte[] buffer = new byte[4096];
                using (FileStream streamReader = File.OpenRead(filename))
                {
                    StreamUtils.Copy(streamReader, zipStream, buffer);
                }
                zipStream.CloseEntry();
            }
            string[] folders = Directory.GetDirectories(path);
            foreach (string folder in folders)
            {
                CompressFolder(folder, zipStream);
            }
        }
 public ExtendedData(string fileName, string mimeType, ZipFile zipFile, ZipEntry extendedZipEntry)
 {
     FileName = fileName;
     MimeType = mimeType;
     _ExtendedZipEntry = extendedZipEntry;
     _ZipFile = zipFile;
 }
        public void Copying()
        {
            long testCrc = 3456;
            long testSize = 99874276;
            long testCompressedSize = 72347;
            byte[] testExtraData = new byte[] { 0x00, 0x01, 0x00, 0x02, 0x0EF, 0xFE };
            string testName = "Namu";
            int testFlags = 4567;
            long testDosTime = 23434536;
            CompressionMethod testMethod = CompressionMethod.Deflated;

            string testComment = "A comment";

            ZipEntry source = new ZipEntry(testName);
            source.Crc = testCrc;
            source.Comment = testComment;
            source.Size = testSize;
            source.CompressedSize = testCompressedSize;
            source.ExtraData = testExtraData;
            source.Flags = testFlags;
            source.DosTime = testDosTime;
            source.CompressionMethod = testMethod;

#pragma warning disable 0618
            ZipEntry clone = new ZipEntry(source);
#pragma warning restore

            PiecewiseCompare(source, clone);
        }
示例#29
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();
                }
            }
        }
示例#30
0
        /*		/// <summary>
         * /// Упаковка папки
         * /// </summary>
         * /// <param name="SourceFolder">путь к исходной папке</param>
         * /// <param name="DestinationZipFile">путь к результирующему zip-архиву</param>
         * /// <param name="CompressLevel">0-9, 9 being the highest level of compression</param>
         * /// <param name="Password">пароль архива. Если его нет, то задаем null</param>
         * /// <param name="BufferSize">буфер, обычно 4096</param>
         */
//		public void ZipFolder(string SourceFolder, string DestinationZipFile, int CompressLevel, string Password, int BufferSize)
//		{
//			List<string> DirList = new List<string>();
//			DirsParser( SourceFolder, ref DirList, false );
//
//			FileStream outputFileStream = new FileStream(DestinationZipFile, FileMode.Create);
//			ZipOutputStream zipOutStream = new ZipOutputStream(outputFileStream);
//			zipOutStream.SetLevel(CompressLevel);
//
//			bool IsCrypted = false;
//			if (Password != null && Password.Length > 0) {
//				zipOutStream.Password = Password;
//				IsCrypted = true;
//			}
//
//			foreach( string dir in DirList ) {
//				string[] FilesForZipList = Directory.GetFiles( dir );
//				if (FilesForZipList.Length == 0) {
//					// файлов нет. Создаем папку dir
//
//				}
//
//				foreach (string file in FilesForZipList) {
//					Stream inputStream = new FileStream(file, FileMode.Open);
//					ZipEntry zipEntry = new ZipEntry(Path.GetFileName(file));
//
//					//zipEntry.IsVisible = IsVisible;
//					zipEntry.IsCrypted = IsCrypted;
//					zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
//					zipOutStream.PutNextEntry(zipEntry);
//					CopyStream(inputStream, zipOutStream, BufferSize);
//					inputStream.Close();
//					zipOutStream.CloseEntry();
//				}
//				zipOutStream.Finish();
//				zipOutStream.Close();
//			}
//		}

        //        public void AddFilesToZip(ref List<string> FilesForZipList, string DestinationZipFile, string Password, bool IsVisible, int BufferSize)
//		{
//			if (FilesForZipList.Count > 0){
        //              FileStream outputFileStream = new FileStream(DestinationZipFile, FileMode.Create);
        //              ZipOutputStream zipOutStream = new ZipOutputStream(outputFileStream);
        //              ZipFile zipFile = null;
//				// there may be files to copy from annother archive
//				zipFile = new ZipFile(DestinationZipFile);
//
//				bool IsCrypted = false;
//				if (Password != null && Password.Length > 0) {
//					zipFile.Password = Password;
//					// encrypt the zip file, if Password != null
//					zipOutStream.Password = Password;
//					IsCrypted = true;
//				}
//
//				foreach (string file in FilesForZipList) {
//					ZipEntry zipEntry = viewItem.Tag as ZipEntry;
//					Stream inputStream;
//					if (zipEntry == null) {
//						inputStream = new FileStream(file, FileMode.Open);
//						zipEntry = new ZipEntry(Path.GetFileName(file));
//					} else {
//						inputStream = zipFile.GetInputStream(zipEntry);
//					}
//					zipEntry.IsVisible = IsVisible;
//					zipEntry.IsCrypted = IsCrypted;
//					zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
//					zipOutStream.PutNextEntry(zipEntry);
//					CopyStream(inputStream, zipOutStream, BufferSize);
//					inputStream.Close();
//					zipOutStream.CloseEntry();
//				}
//
//				if (zipFile != null) {
//					zipFile.Close();
//				}
//
//				zipOutStream.Finish();
//				zipOutStream.Close();
//			}
//		}
        #endregion

        /* ======================================================================================== */
        /*                                  Распаковка файлов										*/
        /* ======================================================================================== */
        #region  аспаковка файлов

        /// <summary>
        /// Распаковка конкретного файла FileName из zip архива ZipPath
        /// Возвращает: Строку string с данными распакованного файла
        /// </summary>
        /// <param name="ZipPath">Путь к исходному zip-файлу</param>
        /// <param name="FileName">Имя файла, который нужно распаковать</param>
        public string UnZipFileToString(string ZipPath, string FileName)
        {
            MemoryStream ms = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zis = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(
                new FileStream(ZipPath, FileMode.Open)
                );
            ICSharpCode.SharpZipLib.Zip.ZipEntry entry = null;
            while ((entry = zis.GetNextEntry()) != null)
            {
                if (entry.Name.ToLower() == FileName)
                {
                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = zis.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            ms.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            if (ms.Length > 0)
            {
                byte[] bdata = ms.ToArray();
                return(Encoding.GetEncoding(getEncoding(bdata)).GetString(bdata));
            }
            return(string.Empty);
        }
示例#31
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;
        }
        public static void CompressFiles(IEnumerable<ISong> files, string destinationPath)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("Starting creation of zip file : " + destinationPath);
            }

            using (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileStream(destinationPath, FileMode.OpenOrCreate)))
            {
                zipOutputStream.SetLevel(0);
                foreach (ISong song in files)
                {

                    FileInfo fileInfo = new FileInfo(song.MediaFilePath);
                    ZipEntry entry = new ZipEntry(song.Artist.Name + "\\" + song.Album.Name + "\\" + song.Title + fileInfo.Extension);
                    zipOutputStream.PutNextEntry(entry);
                    FileStream fs = File.OpenRead(song.MediaFilePath);

                    byte[] buff = new byte[1024];
                    int n = 0;
                    while ((n = fs.Read(buff, 0, buff.Length)) > 0)
                    {
                        zipOutputStream.Write(buff, 0, n);

                    }
                    fs.Close();
                }
                zipOutputStream.Finish();
            }
            if (log.IsDebugEnabled)
            {
                log.Debug("Zip file created : " + destinationPath);
            }
        }
示例#33
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();
        }
示例#34
0
	public override bool SaveImpl(XmlDocument content, Stream out1) {
		ZipOutputStream zos = null;
		if (out1 is ZipOutputStream)
			zos = (ZipOutputStream) out1;
		else
			zos = new ZipOutputStream(out1);

        ZipEntry partEntry = new ZipEntry(CONTENT_TYPES_PART_NAME);
		try {
			// Referenced in ZIP
            zos.PutNextEntry(partEntry);
			// Saving data in the ZIP file
			
			StreamHelper.SaveXmlInStream(content, out1);
            Stream ins =  new MemoryStream();
            
            byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE];
            while (true) {
                int resultRead = ins.Read(buff, 0, ZipHelper.READ_WRITE_FILE_BUFFER_SIZE);
                if (resultRead == 0) {
                    // end of file reached
                    break;
                } else {
                    zos.Write(buff, 0, resultRead);
                }
            }
			zos.CloseEntry();
		} catch (IOException ioe) {
			logger.Log(POILogger.ERROR, "Cannot write: " + CONTENT_TYPES_PART_NAME
				+ " in Zip !", ioe);
			return false;
		}
		return true;
	}
示例#35
0
 public static  void Zip(string strFile, string strZipFile)
 {
     Crc32 crc1 = new Crc32();
     ZipOutputStream stream1 = new ZipOutputStream(File.Create(strZipFile));
     try
     {
         stream1.SetLevel(6);
         FileStream stream2 = File.OpenRead(strFile);
         byte[] buffer1 = new byte[stream2.Length];
         stream2.Read(buffer1, 0, buffer1.Length);
         ZipEntry entry1 = new ZipEntry(strFile.Split(new char[] { '\\' })[strFile.Split(new char[] { '\\' }).Length - 1]);
         entry1.DateTime = DateTime.Now;
         entry1.Size = stream2.Length;
         stream2.Close();
         crc1.Reset();
         crc1.Update(buffer1);
         entry1.Crc = crc1.Value;
         stream1.PutNextEntry(entry1);
         stream1.Write(buffer1, 0, buffer1.Length);
     }
     catch (Exception exception1)
     {
         throw exception1;
     }
     finally
     {
         stream1.Finish();
         stream1.Close();
         stream1 = null;
         crc1 = null;
     }
 }
示例#36
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();
 }
示例#37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExtensionFile"/> class.
 /// </summary>
 /// <param name="installPath">The path where this file is installed.</param>
 /// <param name="file">The file.</param>
 /// <param name="crcCode">The CRC code of the file.</param>
 public ExtensionFile(string installPath, ZipEntry file, string crcCode)
 {
     this.CrcCode = crcCode;
     this.Entry = file;
     this.Name = file.Name;
     this.InstallPath = installPath;
 }
示例#38
0
        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();
              }
        }
示例#39
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();
            }
        }
示例#40
0
 /// <summary>
 /// 解压缩
 /// </summary>
 /// <param name="zipBytes">待解压数据</param>
 /// <returns></returns>
 public static byte[] UnZip(byte[] zipBytes)
 {
     ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = null;
     ICSharpCode.SharpZipLib.Zip.ZipEntry       ent       = null;
     byte[] reslutBytes = null;
     try
     {
         using (System.IO.MemoryStream inputZipStream = new System.IO.MemoryStream(zipBytes))
         {
             zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(inputZipStream);
             if ((ent = zipStream.GetNextEntry()) != null)
             {
                 reslutBytes = new byte[zipStream.Length];
                 zipStream.Read(reslutBytes, 0, reslutBytes.Length);
             }
         }
     }
     finally
     {
         if (zipStream != null)
         {
             zipStream.Close();
             zipStream.Dispose();
         }
         if (ent != null)
         {
             ent = null;
         }
         GC.Collect();
         GC.Collect(1);
     }
     return(reslutBytes);
 }
示例#41
0
        public static ZipFileSystem CreateZipFile(IFile zipFile, IEnumerable <IFile> files, Func <IFile, string> fileToFullPath, FileSystemOptions options)
        {
            var compressionLevel = 9;

            var zipCompressionLevel = options.Variables["ZipCompressionLevel"];

            if (zipCompressionLevel != null)
            {
                compressionLevel = Convert.ToInt32(zipCompressionLevel);

                if (compressionLevel < 0)
                {
                    compressionLevel = 0;
                }
                else if (compressionLevel > 9)
                {
                    compressionLevel = 9;
                }
            }

            var password = options.Variables["ZipPassword"];

            using (var zipOutputStream = new ZLib.ZipOutputStream(zipFile.GetContent().GetOutputStream()))
            {
                zipOutputStream.SetLevel(compressionLevel);
                zipOutputStream.IsStreamOwner = true;
                zipOutputStream.UseZip64      = ZLib.UseZip64.Dynamic;
                zipOutputStream.Password      = password;

                if (files != null)
                {
                    foreach (var file in files)
                    {
                        var entryName = fileToFullPath(file);
                        entryName = ZLib.ZipEntry.CleanName(entryName);

                        var entry = new ZLib.ZipEntry(entryName);

                        using (var stream = file.GetContent().GetInputStream(FileMode.Open, FileShare.Read))
                        {
                            if (stream.Length > 0)
                            {
                                entry.Size = stream.Length;
                            }

                            zipOutputStream.PutNextEntry(entry);

                            stream.CopyTo(zipOutputStream);
                        }

                        zipOutputStream.CloseEntry();
                    }
                }
            }

            return(new ZipFileSystem(zipFile, options));
        }
示例#42
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());
        }
    }
        /// <summary>
        /// 压缩多个文件/文件夹
        /// </summary>
        /// <param name="comment">注释信息</param>
        /// <param name="password">压缩密码</param>
        /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param>
        /// <param name="filePaths">压缩文件路径</param>
        /// <returns></returns>
        private MemoryStream CreateZip(string comment, string password, int compressionLevel, params string[] filePaths)
        {
            MemoryStream memoryStream = new MemoryStream();

            using (SharpZipLib.ZipOutputStream zipStream = new SharpZipLib.ZipOutputStream(memoryStream))
            {
                if (!string.IsNullOrWhiteSpace(password))
                {
                    zipStream.Password = password;//设置密码
                }

                if (!string.IsNullOrWhiteSpace(comment))
                {
                    zipStream.SetComment(comment);//添加注释
                }

                //设置压缩级别
                zipStream.SetLevel(compressionLevel);

                foreach (string item in filePaths)//从字典取文件添加到压缩文件
                {
                    //如果不是文件直接跳过不打包
                    if (!File.Exists(item))
                    {
                        continue;
                    }

                    FileInfo fileInfo = new FileInfo(item);

                    using (FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        SharpZipLib.ZipEntry zipEntry = new SharpZipLib.ZipEntry(Path.GetFileName(item));

                        zipEntry.DateTime = fileInfo.LastWriteTime;

                        zipEntry.Size = fileStream.Length;

                        zipStream.PutNextEntry(zipEntry);

                        int readLength = 0;

                        byte[] buffer = new byte[bufferSize];

                        do
                        {
                            readLength = fileStream.Read(buffer, 0, bufferSize);
                            zipStream.Write(buffer, 0, readLength);
                        }while (readLength == bufferSize);
                    }
                }
            }

            return(memoryStream);
        }
示例#44
0
    IEnumerator UnpackAsync1(string file, string dir)
    {
        int  index     = 0;
        long hasUnpack = 0;

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        using (FileStream streamRead = File.OpenRead(file))
        {
            byte[]         data = new byte[2048];
            ZipInputStream s    = new ZipInputStream(streamRead);
            ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry = s.GetNextEntry();
            while (theEntry != null)
            {
                index++;
                if (index % 100 == 0)
                {
                    yield return(0);
                }
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);
                if (directoryName != String.Empty)
                {
                    Directory.CreateDirectory(dir + directoryName);
                }
                if (fileName != String.Empty)
                {
                    CurFileName = theEntry.Name;
                    using (FileStream streamWriter = File.Create(dir + theEntry.Name))
                    {
                        int size = s.Read(data, 0, data.Length);
                        while (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                            size = s.Read(data, 0, data.Length);
                        }
                        streamWriter.Close();
                    }
                }
                hasUnpack += theEntry.CompressedSize;
                Progress   = (float)hasUnpack / ( float)streamRead.Length;
                //HasUnPackCount = hasUnpack;
                //TotalUnPackCount = streamRead.Length;
                //Debug.Log(index.ToString()+" "+ hasUnpack +"/" +streamRead.Length);
                theEntry = s.GetNextEntry();
            }
            Progress = 1;
            s.Close();
            GC.Collect();
        }
    }
示例#45
0
    public void PushPasswordButton()
    {
        string pass;
        string text = "";

        pass = pass2Obj.GetComponent <InputField>().text;
        try
        {
            //閲覧するエントリ
            string extractFile = "[system]password[system].txt";

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            try
            {
                if (ze != null)
                {
                    //閲覧するZIPエントリのStreamを取得
                    System.IO.Stream reader = zf.GetInputStream(ze);
                    //文字コードを指定してStreamReaderを作成
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        reader, System.Text.Encoding.GetEncoding("UTF-8"));
                    // テキストを取り出す
                    text = sr.ReadToEnd();
                    //閉じる
                    sr.Close();
                    reader.Close();
                }
            }
            catch { }

            //閉じる
            zf.Close();
        }
        catch
        {
            GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "シナリオファイルに異常があります。";
            return;
        }
        if (text == "" || text == pass)
        {
            GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "MapScene");
        }
        else
        {
            GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "パスワードが違います。"; return;
        }
    }
        public void SetZipEntry(ZLib.ZipEntry value)
        {
            this.zipEntry = value;

            if (this.zipEntry != null)
            {
                this.zipPath = this.zipEntry.Name;
            }
            else
            {
                this.zipPath = this.Address.AbsolutePath.Substring(1);
            }
        }
示例#47
0
        void IZipNode.SetZipEntry(ZLib.ZipEntry value)
        {
            this.ZipEntry = value;

            if (value != null)
            {
                this.ZipPath = value.Name;
            }
            else
            {
                this.ZipPath = this.Address.AbsolutePath.Substring(1);
            }
        }
示例#48
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
         });
     }
 }
示例#49
0
文件: ArcZIP.cs 项目: ziyuejun/GARbro
 public ZipEntry(SharpZip.ZipEntry zip_entry)
 {
     NativeEntry = zip_entry;
     Name        = zip_entry.Name;
     Type        = FormatCatalog.Instance.GetTypeFromName(zip_entry.Name);
     IsPacked    = true;
     // design decision of having 32bit entry sizes was made early during GameRes
     // library development. nevertheless, large files will be extracted correctly
     // despite the fact that size is reported as uint.MaxValue, because extraction is
     // performed by .Net framework based on real size value.
     Size         = (uint)Math.Min(zip_entry.CompressedSize, uint.MaxValue);
     UnpackedSize = (uint)Math.Min(zip_entry.Size, uint.MaxValue);
     Offset       = zip_entry.Offset;
 }
示例#50
0
    //目次ファイルを読み込み、進行度に合わせてファイルを拾ってくる。
    private void LoadMapData(string path)
    {
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //閲覧するZIPエントリのStreamを取得
                System.IO.Stream reader = zf.GetInputStream(ze);
                //文字コードを指定してStreamReaderを作成
                System.IO.StreamReader sr = new System.IO.StreamReader(
                    reader, System.Text.Encoding.GetEncoding("UTF-8"));
                // テキストを取り出す
                string text = sr.ReadToEnd();

                // 読み込んだ目次テキストファイルからstring配列を作成する
                mapData = text.Split('\n');
                //閉じる
                sr.Close();
                reader.Close();
                mapLoad = true;
            }
            else
            {
                obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常");
                ErrorBack();
                mapData = new string[0];
            }
            //閉じる
            zf.Close();
        }
        catch
        {
            obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常");
            ErrorBack();
            mapData = new string[0];
        }
    }
示例#51
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);
        }
示例#52
0
 /// <summary>
 /// 压缩
 /// </summary>
 /// <param name="sourceBytes">待压缩数据</param>
 /// <returns></returns>
 public static byte[] Zip(byte[] sourceBytes)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zs = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
         {
             ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Code")
             {
                 DateTime = DateTime.Now
             };
             zs.PutNextEntry(entry);
             zs.Write(sourceBytes, 0, sourceBytes.Length);
             zs.Flush();
         }
         return(ms.ToArray());
     }
 }
示例#53
0
    public void ScenarioFileCheck(int num, ICSharpCode.SharpZipLib.Zip.ZipFile zf)
    {
        string[] strs;
        strs = mapData[num].Replace("\r", "").Replace("\n", "").Split(',');//strs[11]がシナリオパス
        try
        {
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(strs[11]);

            //参照先のファイルがあるか調べる。なかったら(未)をつける。
            if (ze == null)
            {
                objIB[num].GetComponentInChildren <Text>().text = "(未)" + objIB[num].GetComponentInChildren <Text>().text;
            }
        }
        catch { }
    }
示例#54
0
 public SharpZipLibEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry entry)
 {
     Comment           = entry.Comment;
     CompressedSize    = entry.CompressedSize;
     CompressionMethod = entry.CompressionMethod;
     Crc      = entry.Crc;
     DateTime = entry.DateTime;
     DosTime  = entry.DosTime;
     ExternalFileAttributes = entry.ExternalFileAttributes;
     ExtraData     = entry.ExtraData?.ToArray();
     Flags         = entry.Flags;
     Name          = entry.Name;
     Offset        = entry.Offset;
     Size          = entry.Size;
     Version       = entry.Version;
     VersionMadeBy = entry.VersionMadeBy;
     ZipFileIndex  = entry.ZipFileIndex;
 }
示例#55
0
        public void GetFileInZip(ZipFile zipFile, string fileName, List <string> outResult)
        {
            int totalCount = 0;

            foreach (var entry in zipFile)
            {
                ++totalCount;
                ICSharpCode.SharpZipLib.Zip.ZipEntry e = entry as ICSharpCode.SharpZipLib.Zip.ZipEntry;
                if (e != null)
                {
                    if (e.IsFile)
                    {
                        if (e.Name.EndsWith(fileName))
                        {
                            outResult.Add(zipFile.Name + "/!/" + e.Name);
                        }
                    }
                }
            }
        }
示例#56
0
    //アイテム画像ファイルを拾ってくる。
    private void LoadItem(string path)
    {
        byte[] buffer;
        try
        {
            //閲覧するエントリ
            string extractFile = path;
            ICSharpCode.SharpZipLib.Zip.ZipFile zf;
            //ZipFileオブジェクトの作成
            zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));//説明に書かれてる以外のエラーが出てる。

            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //pngファイルの場合
                if (path.Substring(path.Length - 4) == ".png" || path.Substring(path.Length - 4) == ".PNG" || path.Substring(path.Length - 4) == ".jpg" || path.Substring(path.Length - 4) == ".JPG")
                {
                    //閲覧するZIPエントリのStreamを取得
                    Stream fs = zf.GetInputStream(ze);
                    buffer = ReadBinaryData(fs);//bufferにbyte[]になったファイルを読み込み

                    // 画像を取り出す

                    //byteからTexture2D作成
                    Texture2D texture = new Texture2D(1, 1);
                    texture.LoadImage(buffer);
                    obj6.GetComponent <Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    //閉じる
                    fs.Close();
                }
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
示例#57
0
    //startのタイミングでフリーイベントの一覧表を取得し、条件を満たしているものはボタンを作成(Mapシーン限定)
    private void GetFreeIvent(string path)
    {
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //閲覧するZIPエントリのStreamを取得
                System.IO.Stream reader = zf.GetInputStream(ze);
                //文字コードを指定してStreamReaderを作成
                System.IO.StreamReader sr = new System.IO.StreamReader(
                    reader, System.Text.Encoding.GetEncoding("UTF-8"));
                // テキストを取り出す
                string text = sr.ReadToEnd();
                text = text.Replace("[system]任意イベント", "[system]任意イベントCS");
                // 読み込んだ目次テキストファイルからstring配列を作成する
                mapData = text.Split('\n');
                //閉じる
                sr.Close();
                reader.Close();
            }
            else
            {
                SceneManager.LoadScene("TitleScene");
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
        private static Entry ParseEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry entry, Node root)
        {
            if ((!entry.IsFile) && (!entry.IsDirectory))
            {
                return(null);
            }
            string name     = entry.Name.TrimEnd('/');
            Node   dir      = GetDirectory(name.Substring(0, Math.Max(0, name.LastIndexOf('/'))), root);
            Entry  newEntry = new Entry(entry);

            if (newEntry.Kind == EntryKind.ZipDirectoryEntry)
            {
                newEntry.Node = new Node();
            }
            if (dir == null)
            {
                return(newEntry);
            }
            dir.Nodes.Add(newEntry);
            return(null);
        }
示例#59
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;
     }
 }
示例#60
0
        private string GetFileInZip(ZipFile zipFile, string fileName)
        {
            int totalCount = 0;

            foreach (var entry in zipFile)
            {
                ++totalCount;
                ICSharpCode.SharpZipLib.Zip.ZipEntry e = entry as ICSharpCode.SharpZipLib.Zip.ZipEntry;
                if (e != null)
                {
                    if (e.IsFile)
                    {
                        Debug.LogError("ZIP:" + e.Name);
                        if (e.Name.EndsWith(fileName))
                        {
                            return(zipFile.Name + "/!/" + e.Name);
                        }
                    }
                }
            }
            return(null);
        }