Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRC's on data a byte at a time for all combinations of CRC register values and incoming bytes.
Inheritance: IChecksum
Beispiel #1
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);
         }
     }
 }
Beispiel #2
0
		public RuntimeInfo(CompressionMethod method, int compressionLevel, 
            int size, string password, bool getCrc)
		{
			this.method = method;
			this.compressionLevel = compressionLevel;
			this.password = password;
			this.size = size;
			this.random = false;

			original = new byte[Size];
			if (random) {
				System.Random rnd = new Random();
				rnd.NextBytes(original);
			}
			else {
				for (int i = 0; i < size; ++i) {
					original[i] = (byte)'A';
				}
			}

			if (getCrc) {
				Crc32 crc32 = new Crc32();
				crc32.Update(original, 0, size);
				crc = crc32.Value;
			}
		}
Beispiel #3
0
        public void AddStream(string fileName, Stream stream)
        {
            if (_zipOutputStream == null)
                _zipOutputStream = new ZipOutputStream(File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite));

            //
            // Create a CRC value that identifies the file
            //
            var crc = new Crc32();
            crc.Reset();
            crc.Update((int)stream.Length);

            //
            // Create a Zip Entry 
            //
            var zipEntry = new ZipEntry(fileName);
            zipEntry.DateTime = DateTime.Now;
            zipEntry.Size = stream.Length;
            zipEntry.Crc = crc.Value;

            //
            // Attach the Zip Entry in ZipFile
            //
            _zipOutputStream.PutNextEntry(zipEntry);
            Pump(stream, _zipOutputStream);
            _zipOutputStream.CloseEntry();
            _zipOutputStream.Flush();
        }
Beispiel #4
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();
    }
Beispiel #5
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);
                }
            }
        }
Beispiel #6
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();
        }
Beispiel #7
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);
         }
     }
 }
        //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();
        }
Beispiel #9
0
        /// <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;
            }
        }
Beispiel #10
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;
     }
 }
Beispiel #11
0
        public static string AddZip(string fileName, string zipName, ZipOutputStream s)
        {
            Crc32 crc = new Crc32();
            try
            {
                FileStream fs = File.OpenRead(fileName);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fileName = Path.GetFileName(fileName);
                long fileLength = fs.Length;
                fs.Close();

                ZipEntry entry = new ZipEntry(zipName);
                entry.DateTime = DateTime.Now;
                entry.Size = fileLength;

                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                s.PutNextEntry(entry);
                s.Write(buffer, 0, buffer.Length);

                return string.Empty;
            }
            catch (Exception addEx)
            {
                return addEx.ToString();
            }
        }
        private static void ZipFileDirectory(string[] files, ZipOutputStream z)
        {
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                foreach(string file in files)
                {
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string fileName = Path.GetFileName(file);

                    ZipEntry entry = new ZipEntry(fileName);
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    z.PutNextEntry(entry);
                    z.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if(fs!=null)
                {
                    fs.Close();
                    fs = null;
                }
                GC.Collect();
            }
        }
Beispiel #13
0
 /// <summary>
 /// 在压缩文件中创建一个新的空文件
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="fileSize"></param>
 public void AddFile(string fileName, long fileSize)
 {
     crc = new Crc32();
     crc.Reset();
     entry = new ZipEntry(fileName);
     entry.DateTime = DateTime.Now;
     entry.Size = fileSize;
     zipStream.PutNextEntry(entry);
 }
Beispiel #14
0
 /// <summary>
 /// 将多个文件压缩成一个文件
 /// </summary>
 /// <param name="source">多个文件,采用全路径,例:e:\tmp\tmp1\DD.cs</param>
 /// <param name="descZip">目标ZIP文件路径</param>
 /// <param name="password">密码</param>
 public void File(string[] source, string descZip, string password = null) {
     ZipOutputStream outStream = new ZipOutputStream(System.IO.File.Create(descZip));
     if (!password.IsNullEmpty()) outStream.Password = password;
     Crc32 crc = new Crc32();
     foreach (string info in source) {
         File(info, crc, outStream);
     }
     outStream.Finish();
     outStream.Close();
 }
Beispiel #15
0
 public ZipOutputStream(Stream baseOutputStream, int bufferSize) : base(baseOutputStream, new Deflater(-1, true), bufferSize)
 {
     this.entries = new ArrayList();
     this.crc = new Crc32();
     this.defaultCompressionLevel = -1;
     this.curMethod = CompressionMethod.Deflated;
     this.zipComment = new byte[0];
     this.crcPatchPos = -1L;
     this.sizePatchPos = -1L;
     this.useZip64_ = ICSharpCode.SharpZipLib.Zip.UseZip64.Dynamic;
 }
Beispiel #16
0
        internal void AddZipEntryToZipOutputStream(ZipOutputStream zipOutputStream, string content, string zipEntryName)
		{
            byte[] xmlBytes = m_encoding.GetBytes(content);

			ZipEntry zipEntry = new ZipEntry(zipEntryName);

			zipEntry.Size = xmlBytes.Length;
			zipEntry.DateTime = DateTime.Now;

			Crc32 crc = new Crc32();
			crc.Reset();
			crc.Update(xmlBytes);
			zipEntry.Crc = crc.Value;

			zipOutputStream.PutNextEntry(zipEntry);
			zipOutputStream.Write(xmlBytes, 0, xmlBytes.Length);
			zipOutputStream.CloseEntry();
		}
Beispiel #17
0
 public static bool Compress(string FileName, string ZipFileName)
 {
     ZipOutputStream stream;
     FileStream stream2;
     if (ZipFileName == "")
     {
         ZipFileName = FileName + ".zip";
     }
     Crc32 crc = new Crc32();
     try
     {
         stream = new ZipOutputStream(System.IO.File.Create(ZipFileName));
     }
     catch
     {
         return false;
     }
     stream.SetLevel(6);
     try
     {
         stream2 = System.IO.File.OpenRead(FileName);
     }
     catch
     {
         stream.Finish();
         stream.Close();
         System.IO.File.Delete(ZipFileName);
         return false;
     }
     byte[] buffer = new byte[stream2.Length];
     stream2.Read(buffer, 0, buffer.Length);
     ZipEntry entry = new ZipEntry(FileName.Split(new char[] { '\\' })[FileName.Split(new char[] { '\\' }).Length - 1]);
     entry.DateTime = DateTime.Now;
     entry.Size = stream2.Length;
     stream2.Close();
     crc.Reset();
     crc.Update(buffer);
     entry.Crc = crc.Value;
     stream.PutNextEntry(entry);
     stream.Write(buffer, 0, buffer.Length);
     stream.Finish();
     stream.Close();
     return true;
 }
Beispiel #18
0
        public void ZipFileMain(string[] args)
        {
            string[] filenames = Directory.GetFiles(args[0]);

            Crc32 crc = new Crc32();
            ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));

            s.SetLevel(6); // 0 - store only to 9 - means best compression

            foreach (string file in filenames)
            {
                //打开压缩文件
                FileStream fs = File.OpenRead(file);

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

                entry.DateTime = DateTime.Now;

                // set Size and the crc, because the information
                // about the size and crc should be stored in the header
                // if it is not set it is automatically written in the footer.
                // (in this case size == crc == -1 in the header)
                // Some ZIP programs have problems with zip files that don't store
                // the size and crc in the header.
                entry.Size = fs.Length;
                fs.Close();

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

                entry.Crc = crc.Value;

                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);

            }

            s.Finish();
            s.Close();
        }
Beispiel #19
0
 /// <summary>
 /// 压缩文件
 /// </summary>
 /// <param name="fileName">要压缩的所有文件(完全路径)</param>
 /// <param name="fileName">文件名称</param>
 /// <param name="name">压缩后文件路径</param>
 /// <param name="Level">压缩级别</param>
 public static void ZipFileMain(string[] filenames, string[] fileName, string name, int Level)
 {
     #region MyRegion
     ZipOutputStream s = new ZipOutputStream(File.Create(name));
     Crc32 crc = new Crc32();
     //压缩级别
     s.SetLevel(Level); // 0 - store only to 9 - means best compression
     try
     {
         int m = 0;
         foreach (string file in filenames)
         {
             //打开压缩文件
             FileStream fs = File.OpenRead(file);//文件地址
             byte[] buffer = new byte[fs.Length];
             fs.Read(buffer, 0, buffer.Length);
             //建立压缩实体
             ZipEntry entry = new ZipEntry(fileName[m].ToString());//原文件名
             //时间
             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);
             m++;
         }
     }
     catch
     {
         throw;
     }
     finally
     {
         s.Finish();
         s.Close();
     }
     #endregion
 }
Beispiel #20
0
        /// <summary>
        /// Производит компрессию указанного потока. Сжатые данные добавляются в конец
        /// выходного потока.
        /// </summary>
        /// <param name="fileName">Имя файла (записи в ZIP-потоке).</param>
        /// <param name="srcStream">Поток данных для сжатия.</param>
        public void WriteFile( string fileName, Stream srcStream )
        {
            byte[] buffer = new byte[srcStream.Length];
            srcStream.Read( buffer, 0, buffer.Length );

            // контрольная сумма
            Crc32 crc = new Crc32();
            crc.Reset();
            crc.Update( buffer );

            // добавить запись о файле в результирующий поток
            ZipEntry entry = new ZipEntry( fileName );
            entry.DateTime = DateTime.Now;
            entry.Size = srcStream.Length;
            entry.Crc = crc.Value;
            m_zipStream.PutNextEntry( entry );

            // сжать и записать буфер данных в результирующий поток
            m_zipStream.Write( buffer, 0, buffer.Length );
        }
Beispiel #21
0
 /// <summary>
 /// 功能:压缩一个文件,不包含路径信息
 /// </summary>
 /// <param name="strSrcFile">待压缩文件</param>
 /// <param name="crc">CRC校验</param>
 /// <param name="outStream"></param>
 private void File(string source, Crc32 crc, ZipOutputStream outStream) {
     string strFileName = Path.GetFileName(source); // 文件名,不含路径信息
     #region 读取文件信息
     FileStream fs = System.IO.File.OpenRead(source);
     long iLength = fs.Length;// 文件长度
     byte[] buffer = new byte[iLength];
     fs.Read(buffer, 0, buffer.Length);
     fs.Close();
     #endregion
     ZipEntry entry = new ZipEntry(strFileName);
     entry.CompressionMethod = CompressionMethod.Deflated; // deflate
     entry.DateTime = DateTime.Now;
     entry.Size = iLength;
     #region CRC校验
     crc.Reset();
     crc.Update(buffer);
     entry.Crc = crc.Value;
     #endregion
     outStream.PutNextEntry(entry);
     outStream.Write(buffer, 0, buffer.Length);
 }
Beispiel #22
0
        protected override void _Unir(string fichero, string dirDest)
        {
            CutterTail tailInicial = CutterTail.LoadFromFile (fichero);
            if (tailInicial != null)
            {
                string destino = dirDest + Path.DirectorySeparatorChar + tailInicial.Original;
                long total = tailInicial.FileSize;
                long transferidos = 0;
                Stream fos = UtilidadesFicheros.CreateWriter (destino);
                string ficheroBase = fichero.Substring (0, fichero.Length - 1);
                int contador = 1;
                CutterTail tail = null;
                byte[] buffer = new byte[Consts.BUFFER_LENGTH];
                OnProgress (0, total);
                Crc32 crc = new Crc32 ();
                while ((tail = CutterTail.LoadFromFile (ficheroBase + contador)) != null) {
                    int leidos = 0;
                    int parcial = 0;
                    long fileSize = new FileInfo (ficheroBase + contador).Length;
                    FileStream fis = File.OpenRead (ficheroBase + contador);

                    crc.Reset ();
                    while ((leidos = fis.Read (buffer, 0, Math.Min ((int)fileSize - CutterTail.TAIL_SIZE - parcial, buffer.Length))) > 0)
                    {
                        fos.Write (buffer, 0, leidos);
                        crc.Update (buffer, 0, leidos);
                        parcial += leidos;
                        transferidos += leidos;
                    }
                    fis.Close ();
                    if (crc.Value != tail.Crc)
                    {
                        throw new Dalle.Formatos.ChecksumVerificationException ("checksum failed on file " + contador, ficheroBase + contador );
                    }
                    contador++;
                }
                fos.Close();
            }
        }
		// ------------------------------------------------------------------

		/// <summary>
		/// Compress a folder with multiple files and subfolders with
		/// the ZIP algorithm. Use the DecompressFolder() routine to
		/// decompress the compressed bytes.
		/// </summary>
		/// <param name="folderPath">The path to the folder
		/// that will be compressed.</param>
		/// <returns>Returns the compressed folder contents.</returns>
		public static byte[] CompressFolder(
			string folderPath )
		{
			if ( folderPath == null || folderPath.Length <= 0 )
			{
				return null;
			}
			else
			{
				using ( MemoryStream buf = new MemoryStream() )
				using ( ZipOutputStream zip = new ZipOutputStream( buf ) )
				{
					Crc32 crc = new Crc32();
					zip.SetLevel( 9 );	// 0..9.

					DoCompressFolder(
						buf,
						zip,
						crc,
						folderPath,
						folderPath );

					zip.Finish();

					// --

					byte[] c = new byte[buf.Length];
					buf.Seek( 0, SeekOrigin.Begin );
					buf.Read( c, 0, c.Length );

					// --

					zip.Close();

					return c;
				}
			}
		}
        /// <summary>
        /// Compress a byte array with the ZIP algorithm.
        /// Use the DecompressBytes() routine to decompress the compressed bytes.
        /// </summary>
        /// <param name="input">The bytes to compress.</param>
        /// <returns>Returns the compressed bytes.</returns>
        public static byte[] CompressBytes(
            byte[] input)
        {
            using (MemoryStream buf = new MemoryStream())
            using (ZipOutputStream zip = new ZipOutputStream(buf))
            {
                Crc32 crc = new Crc32();
                zip.SetLevel(9);	// 0..9.

                ZipEntry entry = new ZipEntry(string.Empty);
                entry.DateTime = DateTime.Now;
                entry.Size = input.Length;

                crc.Reset();
                crc.Update(input);

                entry.Crc = crc.Value;

                zip.PutNextEntry(entry);

                zip.Write(input, 0, input.Length);
                zip.Finish();

                // --

                byte[] c = new byte[buf.Length];
                buf.Seek(0, SeekOrigin.Begin);
                buf.Read(c, 0, c.Length);

                // --

                zip.Close();

                return c;
            }
        }
Beispiel #25
0
 public static void ZipFileDictory(string[] args)
 {
     string[] files = Directory.GetFiles(args[0]);
       Crc32 crc32 = new Crc32();
       ZipOutputStream zipOutputStream = new ZipOutputStream((Stream) File.Create(args[1]));
       zipOutputStream.SetLevel(6);
       foreach (string str in files)
       {
     FileStream fileStream = File.OpenRead(str);
     byte[] buffer = new byte[fileStream.Length];
     fileStream.Read(buffer, 0, buffer.Length);
     ZipEntry entry = new ZipEntry(str);
     entry.DateTime = DateTime.Now;
     entry.Size = fileStream.Length;
     fileStream.Close();
     crc32.Reset();
     crc32.Update(buffer);
     entry.Crc = crc32.Value;
     zipOutputStream.PutNextEntry(entry);
     zipOutputStream.Write(buffer, 0, buffer.Length);
       }
       zipOutputStream.Finish();
       zipOutputStream.Close();
 }
Beispiel #26
0
 /// <summary>
 /// ZipFileMain
 /// </summary>
 /// <param name="args"></param>
 public static void ZipFileMain(string[] args)
 {
     string[] filenames = Directory.GetFiles(args[0]);
     Crc32 crc = new Crc32();
     ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
     s.SetLevel(6); // 0 - store only to 9 - means best compression
     foreach (string file in filenames)
     {
         FileStream fs = File.OpenRead(file);
         byte[] buffer = new byte[fs.Length];
         fs.Read(buffer, 0, buffer.Length);
         ZipEntry entry = new ZipEntry(file);
         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);
     }
     s.Finish();
     s.Close();
 }
Beispiel #27
0
        /// <summary>
        /// Internal private hashing method.
        /// 
        /// This is the new hashing algorithm from other clients.
        /// Found to be fast and have very good distribution. 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static int NewCompatHashingAlg(string key)
        {
            Crc32 checksum = new Crc32();

            checksum.Update(UTF8Encoding.UTF8.GetBytes(key));

            int crc = (int) checksum.Value;

            return (crc >> 16) & 0x7fff;
        }
Beispiel #28
0
 public static byte[] ZipMultiFiles(int CompressLevel, bool isWithoutFilePathInfo, params string[] FileNames)
 {
     ZipOutputStream stream = null;
     FileStream stream2 = null;
     MemoryStream baseOutputStream = new MemoryStream();
     bool flag = false;
     try
     {
         Crc32 crc = new Crc32();
         stream = new ZipOutputStream(baseOutputStream);
         stream.SetLevel(CompressLevel);
         foreach (string str in FileNames)
         {
             if (System.IO.File.Exists(str))
             {
                 stream2 = System.IO.File.OpenRead(str);
                 byte[] buffer = new byte[stream2.Length];
                 stream2.Read(buffer, 0, buffer.Length);
                 stream2.Close();
                 crc.Reset();
                 crc.Update(buffer);
                 ZipEntry entry = new ZipEntry(isWithoutFilePathInfo ? Path.GetFileName(str) : str);
                 entry.DateTime = DateTime.Now;
                 entry.Size = buffer.Length;
                 entry.Crc = crc.Value;
                 stream.PutNextEntry(entry);
                 stream.Write(buffer, 0, buffer.Length);
             }
         }
         flag = true;
     }
     catch
     {
     }
     finally
     {
         if (stream2 != null)
         {
             stream2.Close();
         }
         if (stream != null)
         {
             stream.Finish();
             stream.Close();
         }
     }
     byte[] buffer2 = null;
     if (flag)
     {
         buffer2 = baseOutputStream.GetBuffer();
     }
     return buffer2;
 }
Beispiel #29
0
		/// <summary>
		/// Closes the zip input stream
		/// </summary>
		public override void Close()
		{
			base.Close();
			crc = null;
			entry = null;
		}
Beispiel #30
0
        /// <summary>
        /// Builds the update and stores it in the system's database.
        /// </summary>
        /// <returns>True if the operation succeeds, false otherwise.</returns>
        private bool AddUpdate()
        {
            bool retVal = false;
            try
            {
                byte [] buffer = new byte[0];
                FileStream ifs = null;
                FileInfo fi = null;
                MemoryStream oms = new MemoryStream();
                Crc32 crc = new Crc32();
                ZipOutputStream zs = new ZipOutputStream(oms);
                int numFiles = lstFiles.Items.Count;
                for(int i = 0; i<numFiles ; i++)
                {
                    string entryName = Path.GetFileName(lstFiles.Items[i].SubItems[0].Text);
                    fi = new FileInfo(lstFiles.Items[i].SubItems[0].Text);
                    ifs = File.OpenRead(lstFiles.Items[i].SubItems[0].Text);
                    buffer = new byte[fi.Length];
                    ifs.Read(buffer, 0, buffer.Length);
                    ZipEntry entry = new ZipEntry(entryName);
                    entry.DateTime = fi.LastWriteTime;
                    entry.Size = fi.Length;
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zs.PutNextEntry(entry);
                    zs.Write(buffer, 0, buffer.Length);
                    prgProgress.Value = (int)(((i+1)*80)/numFiles);
                }
                zs.Finish();
                zs.Close();

                buffer = oms.ToArray();
                oms.Close();

                //Connect to the database
                SqlConnection dbcon = null;
                try
                {
                    dbcon = new SqlConnection(globals.ProvideConnectionString());
                    dbcon.Open();
                }
                catch(Exception ex)
                {
                    if(dbcon != null)
                    {
                        dbcon.Dispose();
                        dbcon = null;
                    }
                    throw ex;
                }
                prgProgress.Value = 85;
                SqlCommand cmd = new SqlCommand("cw_insert_client_update", dbcon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@client_update_version", SqlDbType.Char, 15);
                cmd.Parameters.Add("@client_update_image", SqlDbType.Image);
                Version latestVersion = new Version(txtNewVersion.Text);
                cmd.Parameters[0].Value = latestVersion.ToString();
                cmd.Parameters[1].Value = buffer;
                prgProgress.Value = 90;
                cmd.ExecuteNonQuery();
                dbcon.Close();
                prgProgress.Value = 100;
                lblLatestVersionVal.Text = latestVersion.ToString();
                retVal = true;
            }
            catch(Exception e)
            {
                globals.Log.LogError("CrawlWave.ServerManager failed to create an update: " + e.ToString());
                MessageBox.Show(this.Text + " failed to create and update:\n" + e.Message);
                retVal = false;
            }
            finally
            {
                GC.Collect();
            }
            return retVal;
        }
		private void CreateZipFile(string img_quality)
		{
			string[] filenames = Directory.GetFiles(SubdirPath (img_quality));
			Crc32 crc = new Crc32();
			ZipOutputStream s = new ZipOutputStream(File.Create(SubdirPath ("zip", img_quality + ".zip")));
			
			s.SetLevel(0);
			foreach (string file in filenames) {
				FileStream fs = File.OpenRead(file);
			
				byte[] buffer = new byte[fs.Length];
				fs.Read(buffer, 0, buffer.Length);
				ZipEntry entry = new ZipEntry(Path.GetFileName(file));
			
				entry.DateTime = DateTime.Now;
			
				// set Size and the crc, because the information
				// about the size and crc should be stored in the header
				// if it is not set it is automatically written in the footer.
				// (in this case size == crc == -1 in the header)
				// Some ZIP programs have problems with zip files that don't store
				// the size and crc in the header.
				entry.Size = fs.Length;
				fs.Close();
			
				crc.Reset();
				crc.Update(buffer);
			
				entry.Crc  = crc.Value;
			
				s.PutNextEntry(entry);
			
				s.Write(buffer, 0, buffer.Length);
			
			}
		
			s.Finish();
			s.Close();
		}