示例#1
0
        public void CreateZipOfSingleFileWithOutputPath(string inputFilePath, string outputFilePath, string password = "")
        {
            if (inputFilePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                throw new InvalidDirectoryPathException();
            }
            if (outputFilePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                throw new InvalidDirectoryPathException();
            }
            int trimLength = (Directory.GetParent(inputFilePath)).ToString().Length;

            trimLength += 1;

            byte[] obuffer;

            using (var oZipStream = new ZipOutputStream(DirectoryOperationsHelper.Create(outputFilePath)))
            {
                oZipStream.SetLevel(3); // maximum compression

                if (!string.IsNullOrEmpty(password))
                {
                    oZipStream.Password = password;
                }

                var fileInfo = new FileInfo(inputFilePath);

                var oZipEntry = new ZipEntry(inputFilePath.Remove(0, trimLength));
                oZipEntry.DateTime = fileInfo.LastWriteTime;
                oZipEntry.Size     = fileInfo.Length;

                oZipStream.UseZip64 = UseZip64.Off;
                oZipStream.PutNextEntry(oZipEntry);

                if (!inputFilePath.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    using (var ostream = DirectoryOperationsHelper.OpenRead(inputFilePath))
                    {
                        obuffer = new byte[ostream.Length];
                        ostream.Read(obuffer, 0, obuffer.Length);
                        oZipStream.Write(obuffer, 0, obuffer.Length);

                        ostream.Close();
                    }
                }
                oZipStream.CloseEntry();
                oZipStream.Finish();
                oZipStream.Close();
            }
        }