Exemplo n.º 1
2
        /// <summary>
        /// Creates a zip archive from a byte array
        /// </summary>
        /// <param name="buffer">The file in byte[] format</param>
        /// <param name="fileName">The name of the file you want to add to the archive</param>
        /// <returns></returns>
        public static byte[] CreateZipByteArray(byte[] buffer, string fileName)
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

            using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream())
            {
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream);

                zipOutputStream.SetLevel(6);

                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                zipEntry.DateTime = DateTime.Now;
                zipEntry.Size = buffer.Length;

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

                zipOutputStream.Finish();

                byte[] zipByteArray = new byte[zipMemoryStream.Length];
                zipMemoryStream.Position = 0;
                zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length);

                zipOutputStream.Close();

                return zipByteArray;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// calculate crc of the audio data
        /// </summary>
        public override uint CalculateAudioCRC32()
        {
            using (Stream stream = OpenAudioStream())
            {
                ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

                uint numLeft = _payloadNumBytes;

                const int size  = 4096;
                byte[]    bytes = new byte[4096];
                int       numBytes;

                while (numLeft > 0)
                {
                    // read a whole block, or to the end of the file
                    numBytes = stream.Read(bytes, 0, size);

                    // audio ends on or before end of this read; exit loop and checksum what we have.
                    if (numLeft <= numBytes)
                    {
                        break;
                    }

                    crc.Update(bytes, 0, numBytes);
                    numLeft -= (uint)numBytes;
                }

                crc.Update(bytes, 0, (int)numLeft);
                uint result = (uint)crc.Value;
                return(result);
            }
        }
Exemplo n.º 3
0
		/// <summary>
		/// Replaces the specified shader data.
		/// </summary>
		/// <param name="file">The shader file whose data is to be replaced.</param>
		/// <param name="shader">The shader in the file that is to be replaced.</param>
		/// <param name="newdata">The data with which to replaced the existing shader data.</param>
		/// <param name="OldData">Returns the existing shader data.</param>
		/// <param name="crc">The CRC of the new shader data. Used to verify the replacement; use 0 if no validation is desired.</param>
		/// <returns><c>true</c> if the shader was replaced; <c>false</c> otherwise.</returns>
		private bool ReplaceShader(string file, string shader, byte[] newdata, out byte[] OldData, uint crc)
		{
			string tempshader = Path.Combine(m_futFileUtility.CreateTempDirectory(), "tempshader");

			DateTime timeStamp = File.GetLastWriteTime(file);
			File.Delete(tempshader);
			File.Move(file, tempshader);
			BinaryReader br = new BinaryReader(File.OpenRead(tempshader), System.Text.Encoding.Default);
			BinaryWriter bw = new BinaryWriter(File.Create(file), System.Text.Encoding.Default);
			bw.Write(br.ReadInt32());
			int num = br.ReadInt32();
			bw.Write(num);
			long sizeoffset = br.BaseStream.Position;
			bw.Write(br.ReadInt32());
			bool found = false;
			OldData = null;
			for (int i = 0; i < num; i++)
			{
				char[] name = br.ReadChars(0x100);
				int size = br.ReadInt32();
				byte[] data = br.ReadBytes(size);

				bw.Write(name);
				string sname = "";
				for (int i2 = 0; i2 < 100; i2++) { if (name[i2] == '\0') break; sname += name[i2]; }
				if (!found && sname == shader)
				{
					ICSharpCode.SharpZipLib.Checksums.Crc32 ccrc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
					ccrc.Update(data);
					if (crc == 0 || ccrc.Value == crc)
					{
						bw.Write(newdata.Length);
						bw.Write(newdata);
						found = true;
						OldData = data;
					}
					else
					{
						bw.Write(size);
						bw.Write(data);
					}
				}
				else
				{
					bw.Write(size);
					bw.Write(data);
				}
			}
			bw.BaseStream.Position = sizeoffset;
			bw.Write((int)(bw.BaseStream.Length - 12));
			br.Close();
			bw.Close();
			File.Delete(tempshader);
			File.SetLastWriteTime(file, timeStamp);
			return found;
		}
Exemplo n.º 4
0
        // 파일의 CRC 값 반환
        Int64 GetCRC(string FileName)
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

            System.IO.FileStream fs1 = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            byte[] buffer1           = new byte[fs1.Length];
            fs1.Read(buffer1, 0, buffer1.Length);
            fs1.Close();
            crc.Reset();
            crc.Update(buffer1);
            return(crc.Value);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Verifies if the data within the file segment has the same CRC32
        /// checksum as the one written in the headers. If it isn't, the data
        /// may be corrupt.
        /// </summary>
        /// <returns>TRUE if the data is considered intact, FALSE otherwise.</returns>
        public bool VerifyData()
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 checksum = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            checksum.Reset();

            br.BaseStream.Position = GetDataPosition(true);
            ICSharpCode.SharpZipLib.BZip2.BZip2InputStream bzis = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(br.BaseStream);
            byte[] buffer = new byte[4096];
            int    i      = 0;

            while ((i = bzis.Read(buffer, 0, 4096)) > 0)
            {
                checksum.Update(buffer, 0, i);
            }

            return(checksum.Value == nCRCSum);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Compacta a lista de Arquivos criando o arquivo zip passado como parâmetro
        /// </summary>
        /// <param name="filesName">Lista de arquivos a serem incluidos no .zip</param>
        /// <param name="strArquivoZip">Nome do arquivo .zip</param>
        public void compacta(ref System.Collections.ArrayList filesName, string strArquivoZip)
        {
            try
            {
                ICSharpCode.SharpZipLib.Checksums.Crc32     clsCrc          = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream clsZipOutStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(strArquivoZip));

                clsZipOutStream.SetLevel(m_nNivelCompressao);

                foreach (string file in filesName)
                {
                    System.IO.FileStream fs = System.IO.File.OpenRead(file);

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

                    entry.DateTime = DateTime.Now;

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

                    clsCrc.Reset();
                    clsCrc.Update(buffer);

                    entry.Crc = clsCrc.Value;

                    clsZipOutStream.PutNextEntry(entry);

                    clsZipOutStream.Write(buffer, 0, buffer.Length);
                }
                clsZipOutStream.Finish();
                clsZipOutStream.Close();
            }
            catch (Exception err)
            {
                Object erro = err;
                m_cls_ter_tratadorErro.trataErro(ref erro);
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// 只有一个方法
 /// </summary>
 public bool StartZip()
 {
     using (zos = new ZipOutputStream(System.IO.File.Create(destFileName)))
     {
         try
         {
             m_Crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
             addZipEntryONE(sourcePath);
             return(true);
         }
         catch (Exception ex)
         {
             WriteLog("压缩文件失败!错误信息:" + ex.Message);
             return(false);
         }
         finally
         {
             zos.Finish();
             zos.Close();
             zos.Dispose();
         }
     }
 }
Exemplo n.º 8
0
        public int CalculateCrc()
        {
            if (!IsValid)
            {
                return(0);
            }

            using (MemoryStream stream = new MemoryStream())
            {
                // serialise tags to a buffer, without any padding
                FrameManager.Serialize(this, stream);

                // obtain whole buffer as byte array
                byte[] buffer = stream.ToArray();

                // calculate the size of the tag without the padding
                int tagsize = (int)buffer.Length - (int)Header.PaddingSize;

                // create and calculate crc-32 for the tag
                ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                crc.Update(buffer, 0, tagsize);
                return((int)crc.Value);
            }
        }
Exemplo n.º 9
0
        private static void ZipDirectoryToZipStream(ZipOutputStream outStream, string directoryPath, string parentPath)
        {
            try
            {
                if (directoryPath == string.Empty)
                {
                    return;
                }

                if (directoryPath[directoryPath.Length - 1] != '/')
                {
                    directoryPath += '/';
                }

                if (parentPath[parentPath.Length - 1] != '/')
                {
                    parentPath += '/';
                }

                ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                string[] filePaths = Directory.GetFileSystemEntries(directoryPath);

                foreach (string path in filePaths)
                {
                    var filePath = path.Replace('\\', '/');
                    if (Directory.Exists(filePath)) // 是目录
                    {
                        string pPath = parentPath + filePath.Substring(filePath.LastIndexOf('/') + 1);
                        pPath += '/';
                        ZipDirectoryToZipStream(outStream, filePath, pPath);
                    }
                    else
                    {
                        using (FileStream inStream = File.OpenRead(filePath))
                        {
                            byte[] buffer = new byte[inStream.Length];
                            inStream.Read(buffer, 0, buffer.Length);
                            inStream.Close();

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

                            string   entryPath = parentPath + filePath.Substring(filePath.LastIndexOf('/') + 1);
                            ZipEntry zipEntry  = new ZipEntry(entryPath);
                            FileInfo fileInfo  = new FileInfo(filePath);

                            zipEntry.DateTime = fileInfo.CreationTime > fileInfo.LastWriteTime ? fileInfo.LastWriteTime : fileInfo.CreationTime;
                            zipEntry.Size     = fileInfo.Length;
                            zipEntry.Crc      = crc.Value;

                            outStream.PutNextEntry(zipEntry);
                            outStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// calculate crc of the audio data
        /// </summary>
        public override uint CalculateAudioCRC32()
        {
            using (Stream stream = OpenAudioStream())
            {
                ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

                uint numLeft = _payloadNumBytes;

                const int size = 4096;
                byte[] bytes = new byte[4096];
                int numBytes;

                while (numLeft > 0)
                {
                    // read a whole block, or to the end of the file
                    numBytes = stream.Read(bytes, 0, size);

                    // audio ends on or before end of this read; exit loop and checksum what we have.
                    if (numLeft <= numBytes)
                        break;

                    crc.Update(bytes, 0, numBytes);
                    numLeft -= (uint)numBytes;
                }

                crc.Update(bytes, 0, (int)numLeft);
                uint result = (uint)crc.Value;
                return result;
            }
        }
Exemplo n.º 11
0
        private static void Zip(string[] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream s)
        {
            List <string> rootPaths = new List <string>();

            ICSharpCode.SharpZipLib.Zip.ZipEntry entry = null;
            System.IO.FileStream fs = null;
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            try
            {
                ////创建当前文件夹
                //entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("/");  //加上 “/” 才会当成是文件夹创建
                //s.PutNextEntry(entry);
                //s.Flush();
                foreach (string file in files)
                {
                    if (System.IO.Directory.Exists(file))
                    {
                        if (file.Split('\\').Count() > 1)
                        {
                            rootPaths.Add(file);
                            entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Split('\\').Last() + "/");  //加上 “/” 才会当成是文件夹创建
                            s.PutNextEntry(entry);
                            s.Flush();
                        }
                        continue;
                    }

                    //打开压缩文件
                    fs = System.IO.File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    var zipfilename = System.IO.Path.GetFileName(file);
                    foreach (var rootPath in rootPaths)
                    {
                        var _index = file.IndexOf(rootPath);
                        if (_index >= 0)
                        {
                            zipfilename = rootPath.Split('\\').Last() + "\\" + System.IO.Path.GetFileName(file);
                            break;
                        }
                    }
                    entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipfilename)
                    {
                        DateTime = DateTime.Now,
                        Size     = fs.Length
                    };
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Replaces the specified shader data.
        /// </summary>
        /// <param name="file">The shader file whose data is to be replaced.</param>
        /// <param name="shader">The shader in the file that is to be replaced.</param>
        /// <param name="newdata">The data with which to replaced the existing shader data.</param>
        /// <param name="OldData">Returns the existing shader data.</param>
        /// <param name="crc">The CRC of the new shader data. Used to verify the replacement; use 0 if no validation is desired.</param>
        /// <returns><c>true</c> if the shader was replaced; <c>false</c> otherwise.</returns>
        private bool ReplaceShader(string file, string shader, byte[] newdata, out byte[] OldData, uint crc)
        {
            string tempshader = Path.Combine(m_futFileUtility.CreateTempDirectory(), "tempshader");

            DateTime timeStamp = File.GetLastWriteTime(file);

            File.Delete(tempshader);
            File.Move(file, tempshader);
            BinaryReader br = new BinaryReader(File.OpenRead(tempshader), System.Text.Encoding.Default);
            BinaryWriter bw = new BinaryWriter(File.Create(file), System.Text.Encoding.Default);

            bw.Write(br.ReadInt32());
            int num = br.ReadInt32();

            bw.Write(num);
            long sizeoffset = br.BaseStream.Position;

            bw.Write(br.ReadInt32());
            bool found = false;

            OldData = null;
            for (int i = 0; i < num; i++)
            {
                char[] name = br.ReadChars(0x100);
                int    size = br.ReadInt32();
                byte[] data = br.ReadBytes(size);

                bw.Write(name);
                string sname = "";
                for (int i2 = 0; i2 < 100; i2++)
                {
                    if (name[i2] == '\0')
                    {
                        break;
                    }
                    sname += name[i2];
                }
                if (!found && sname == shader)
                {
                    ICSharpCode.SharpZipLib.Checksums.Crc32 ccrc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                    ccrc.Update(data);
                    if (crc == 0 || ccrc.Value == crc)
                    {
                        bw.Write(newdata.Length);
                        bw.Write(newdata);
                        found   = true;
                        OldData = data;
                    }
                    else
                    {
                        bw.Write(size);
                        bw.Write(data);
                    }
                }
                else
                {
                    bw.Write(size);
                    bw.Write(data);
                }
            }
            bw.BaseStream.Position = sizeoffset;
            bw.Write((int)(bw.BaseStream.Length - 12));
            br.Close();
            bw.Close();
            File.Delete(tempshader);
            File.SetLastWriteTime(file, timeStamp);
            return(found);
        }
Exemplo n.º 13
0
        private void ZipDirectory(string zipfile, string folder, string comment, List<KeyValuePair<string, string>> filemap)
        {
            ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = System.Text.Encoding.UTF8.CodePage;
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            using (System.IO.FileStream ofs = new System.IO.FileStream(zipfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ofs))
            {
                try
                {
                    zip.SetLevel(9);
                    if (!string.IsNullOrEmpty(comment))
                        zip.SetComment(comment);

                    int i = 0;

                    foreach (KeyValuePair<string, string> f in filemap)
                    {
                        if (Progress != null)
                            Progress(ProgressType.Compressing, f.Key, filemap.Count, i);

                        System.IO.FileInfo fi = new System.IO.FileInfo(f.Value);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(RelativeName(f.Key, folder).Replace('\\', '/'));
                        ze.DateTime = fi.LastWriteTime;
                        ze.Size = fi.Length;
                        zip.PutNextEntry(ze);
                        using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                            Utility.CopyStream(fs, zip);

                        if (Progress != null)
                            Progress(ProgressType.Compressing, f.Key, filemap.Count, i++);
                    }

                    zip.Finish();
                }
                finally
                {
                    try { zip.Close(); }
                    catch { }
                }
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// calculate crc of the audio data
 /// </summary>
 public override uint CalculateAudioCRC32()
 {
     ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
     crc.Update(_sourceBuffer);
     return((uint)crc.Value);
 }
Exemplo n.º 15
0
 /// <summary>
 /// calculate crc of the audio data
 /// </summary>
 public override uint CalculateAudioCRC32()
 {
     ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
     crc.Update(_sourceBuffer);
     return (uint)crc.Value;
 }
Exemplo n.º 16
0
        /// <summary>
        /// 递归压缩文件夹方法
        /// </summary>
        private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName, List <DirectoryInfo> eliminateInfos,
                                           List <FileInfo> eliminateFileInfos)
        {
            bool res = true;

            string[]   folders, filenames;
            ZipEntry   entry = null;
            FileStream fs    = null;

            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
            try
            {
                entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
                s.PutNextEntry(entry);
                s.Flush();
                filenames = Directory.GetFiles(folderToZip);
                foreach (string file in filenames)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    if (eliminateFileInfos.Contains(fileInfo))
                    {
                        continue;
                    }


                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string folderZipName = Path.GetFileName(folderToZip);
                    folderZipName  = string.IsNullOrEmpty(folderZipName) ? string.Empty : string.Concat(folderZipName, "/");
                    entry          = new ZipEntry(Path.Combine(parentFolderName, folderZipName + Path.GetFileName(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);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            folders = Directory.GetDirectories(folderToZip);
            foreach (string folder in folders)
            {
                DirectoryInfo folderInfo = new DirectoryInfo(folder);
                if (eliminateInfos.Contains(folderInfo))
                {
                    continue;
                }

                if (!ZipFileDictory(folder, s
                                    , Path.Combine(parentFolderName, Path.GetFileName(folderToZip)), eliminateInfos, eliminateFileInfos))
                {
                    return(false);
                }
            }
            return(res);
        }