Ejemplo n.º 1
0
        /// <summary>
        /// 压缩单个文件
        /// </summary>
        /// <param name="FileToZip">被压缩的文件名称(包含文件路径)</param>
        /// <param name="ZipedFile">压缩后的文件名称(包含文件路径)</param>
        /// <param name="CompressionLevel">压缩率0(无压缩)-9(压缩率最高)</param>
        /// <param name="BlockSize">缓存大小</param>
        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)
        {
            //如果文件没有找到,则报错
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("文件:" +
                                                          FileToZip + "没有找到!");
            }

            if (ZipedFile == string.Empty)
            {
                ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) +
                            ".zip";
            }

            if (Path.GetExtension(ZipedFile) != ".zip")
            {
                ZipedFile = ZipedFile + ".zip";
            }

            ////如果指定位置目录不存在,创建该目录
            //string zipedDir =
            ZipedFile.Substring(0, ZipedFile.LastIndexOf("/"));
            //if (!Directory.Exists(zipedDir))
            //    Directory.CreateDirectory(zipedDir);

            //被压缩文件名称
            string filename =
                FileToZip.Substring(FileToZip.LastIndexOf("//") + 1);

            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(filename);

            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[]       buffer = new byte[2048];
            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)
            {
                LogHelper.LogWrite(ex);
                throw ex;
            }
            finally
            {
                ZipStream.Finish();
                ZipStream.Close();
                StreamToZip.Close();
            }
        }