UpdateItem() 공개 메소드

Add or update a file or directory in the zip archive.

This is useful when the application is not sure or does not care if the item to be added is a file or directory, and does not know or does not care if the item already exists in the ZipFile. Calling this method is equivalent to calling RemoveEntry() if an entry by the same name already exists, followed calling by AddItem().

For ZipFile properties including Encryption, , SetCompression, , ExtractExistingFile, ZipErrorAction, and CompressionLevel, their respective values at the time of this call will be applied to the ZipEntry added.

public UpdateItem ( string itemName ) : void
itemName string /// the path to the file or directory to be added or updated. ///
리턴 void
예제 #1
0
        public static void Main(String[] args)
        {
            bool saveToStdout = false;
            if (args.Length < 2) Usage();

            if (args[0]=="-")
            {
                saveToStdout = true;
            }
            else if (File.Exists(args[0]))
            {
                System.Console.WriteLine("That zip file ({0}) already exists.", args[0]);
            }


            // Because the comments and filenames on zip entries may be UTF-8
            // System.Console.OutputEncoding = new System.Text.UTF8Encoding();

            Console.CancelKeyPress += CtrlC_Handler;

            try
            {
                Nullable<SelfExtractorFlavor> flavor = null;
                int codePage = 0;
                ZipEntry e = null;
                int _UseUniformTimestamp = 0;
                DateTime _fixedTimestamp= System.DateTime.Now;
                string entryDirectoryPathInArchive = "";
                string directoryOnDisk = null;
                bool recurseDirectories = false;
                bool wantRecurse = false;
                string actualItem;

                // read/update an existing zip, or create a new one.
                using (ZipFile zip = new ZipFile(args[0]))
                {
                    zip.StatusMessageTextWriter = System.Console.Out;
                    zip.SaveProgress += SaveProgress;
                    for (int i = 1; i < args.Length; i++)
                    {
                        switch (args[i])
                        {
                            case "-es":
                                zip.ZipErrorAction = ZipErrorAction.Skip;
                                break;

                            case "-er":
                                zip.ZipErrorAction = ZipErrorAction.Retry;
                                break;

                            case "-eq":
                                zip.ZipErrorAction = ZipErrorAction.Throw;
                                break;

                            case "-ea":
                                zip.ZipError += ZipError;
                                break;

                            case "-64":
                                zip.UseZip64WhenSaving = Zip64Option.Always;
                                break;

                            case "-aes":
                                zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                                break;

                            case "-C":
                                i++;
                                if (args.Length <= i) Usage();
                                switch(args[i].ToLower())
                                {
                                    case "b":
                                    case "bzip":
                                    case "bzip2":
                                        zip.CompressionMethod = CompressionMethod.BZip2;
                                        break;
                                    case "d":
                                    case "deflate":
                                        zip.CompressionMethod = CompressionMethod.Deflate;
                                        break;
                                    case "n":
                                    case "none":
                                        zip.CompressionMethod = CompressionMethod.None;
                                        break;
                                    default:
                                        Usage();
                                        break;
                                }
                                break;

                            case "-cp":
                                i++;
                                if (args.Length <= i) Usage();
                                System.Int32.TryParse(args[i], out codePage);
                                if (codePage != 0)
                                {
                                    zip.AlternateEncoding = System.Text.Encoding.GetEncoding(codePage);
                                    zip.AlternateEncodingUsage = ZipOption.Always;
                                }
                                break;

                            case "-d":
                                i++;
                                if (args.Length <= i) Usage();
                                entryDirectoryPathInArchive = args[i];
                                break;

                            case "-D":
                                i++;
                                if (args.Length <= i) Usage();
                                directoryOnDisk = args[i];
                                break;

                            case "-E":
                                i++;
                                if (args.Length <= i) Usage();
                                wantRecurse = recurseDirectories || args[i].Contains("\\");
                                // Console.WriteLine("spec({0})", args[i]);
                                // Console.WriteLine("dir({0})", directoryOnDisk);
                                // Console.WriteLine("dirInArc({0})", entryDirectoryPathInArchive);
                                // Console.WriteLine("recurse({0})", recurseDirectories);
                                zip.UpdateSelectedFiles(args[i],
                                                        directoryOnDisk,
                                                        entryDirectoryPathInArchive,
                                                        wantRecurse);
                                break;

                            case "-j-":
                                zip.AddDirectoryWillTraverseReparsePoints = false;
                                break;

                            case "-j+":
                                zip.AddDirectoryWillTraverseReparsePoints = true;
                                break;

                            case "-L":
                                i++;
                                if (args.Length <= i) Usage();
                                zip.CompressionLevel = (Ionic.Zlib.CompressionLevel)
                                    System.Int32.Parse(args[i]);
                                break;

                            case "-p":
                                i++;
                                if (args.Length <= i) Usage();
                                zip.Password = (args[i] == "") ? null : args[i];
                                break;

                            case "-progress":
                                wantProgressReports = true;
                                break;

                            case "-r-":
                                recurseDirectories = false;
                                break;

                            case "-r+":
                                recurseDirectories = true;
                                break;

                            case "-s":
                                i++;
                                if (args.Length <= i) Usage();
                                string entryName = args[i];
                                i++;
                                if (args.Length <= i) Usage();
                                string content = args[i];
                                e = zip.AddEntry(Path.Combine(entryDirectoryPathInArchive, entryName), content);
                                //                                 if (entryComment != null)
                                //                                 {
                                //                                     e.Comment = entryComment;
                                //                                     entryComment = null;
                                //                                 }
                                break;

                            case "-sfx":
                                i++;
                                if (args.Length <= i) Usage();
                                if (args[i] != "w" && args[i] != "c") Usage();
                                flavor = new Nullable<SelfExtractorFlavor>
                                    ((args[i] == "w") ? SelfExtractorFlavor.WinFormsApplication : SelfExtractorFlavor.ConsoleApplication);
                                break;

                            case "-split":
                                i++;
                                if (args.Length <= i) Usage();
                                if (args[i].EndsWith("K") || args[i].EndsWith("k"))
                                    zip.MaxOutputSegmentSize = Int32.Parse(args[i].Substring(0, args[i].Length - 1)) * 1024;
                                else if (args[i].EndsWith("M") || args[i].EndsWith("m"))
                                    zip.MaxOutputSegmentSize = Int32.Parse(args[i].Substring(0, args[i].Length - 1)) * 1024 * 1024;
                                else
                                    zip.MaxOutputSegmentSize = Int32.Parse(args[i]);
                                break;

                            case "-Tw+":
                                zip.EmitTimesInWindowsFormatWhenSaving = true;
                                break;

                            case "-Tw-":
                                zip.EmitTimesInWindowsFormatWhenSaving = false;
                                break;

                            case "-Tu+":
                                zip.EmitTimesInUnixFormatWhenSaving = true;
                                break;

                            case "-Tu-":
                                zip.EmitTimesInUnixFormatWhenSaving = false;
                                break;

                            case "-UTnow":
                                _UseUniformTimestamp = 1;
                                _fixedTimestamp = System.DateTime.UtcNow;
                                break;

                            case "-UTnewest":
                                _UseUniformTimestamp = 2;
                                break;

                            case "-UToldest":
                                _UseUniformTimestamp = 3;
                                break;

                            case "-UT":
                                i++;
                                if (args.Length <= i) Usage();
                                _UseUniformTimestamp = 4;
                                try
                                {
                                    _fixedTimestamp= System.DateTime.Parse(args[i]);
                                }
                                catch
                                {
                                    throw new ArgumentException("-UT");
                                }
                                break;

                            case "-utf8":
                                zip.AlternateEncoding = System.Text.Encoding.UTF8;
                                zip.AlternateEncodingUsage = ZipOption.Always;
                                break;

#if NOT
                            case "-c":
                                i++;
                                if (args.Length <= i) Usage();
                                entryComment = args[i];  // for the next entry
                                break;
#endif

                            case "-zc":
                                i++;
                                if (args.Length <= i) Usage();
                                zip.Comment = args[i];
                                break;

                            default:
                                // UpdateItem will add Files or Dirs,
                                // recurses subdirectories
                                actualItem = Path.Combine(directoryOnDisk ?? ".", args[i]);
                                zip.UpdateItem(actualItem, entryDirectoryPathInArchive);
                                break;
                        }
                    }

                    if (_UseUniformTimestamp > 0)
                    {
                        if (_UseUniformTimestamp==2)
                        {
                            // newest
                            _fixedTimestamp = new System.DateTime(1601,1,1,0,0,0);
                            foreach(var entry in zip)
                            {
                                if (entry.LastModified > _fixedTimestamp)
                                    _fixedTimestamp = entry.LastModified;
                            }
                        }
                        else if (_UseUniformTimestamp==3)
                        {
                            // oldest
                            foreach(var entry in zip)
                            {
                                if (entry.LastModified < _fixedTimestamp)
                                    _fixedTimestamp = entry.LastModified;
                            }
                        }

                        foreach(var entry in zip)
                        {
                            entry.LastModified = _fixedTimestamp;
                        }
                    }

                    if (!flavor.HasValue)
                    {
                        if (saveToStdout)
                            zip.Save(Console.OpenStandardOutput());
                        else
                            zip.Save();
                    }
                    else
                    {
                        if (saveToStdout)
                            throw new Exception("Cannot save SFX to stdout, sorry! See http://dotnetzip.codeplex.com/WorkItem/View.aspx?WorkItemId=7246");
                        zip.SaveSelfExtractor(args[0], flavor.Value);

                    }

                }
            }
            catch (System.Exception ex1)
            {
                System.Console.WriteLine("Exception: " + ex1);
            }
        }
예제 #2
0
        public void UpdateZip_UpdateItem()
        {
            string filename = null;
            int entriesAdded = 0;
            string repeatedLine = null;
            int j;

            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem.zip");

            // create the subdirectory
            string subdir = Path.Combine(TopLevelDir, "A");
            Directory.CreateDirectory(subdir);

            // create a bunch of files
            int numFilesToCreate = _rnd.Next(10) + 8;
            for (j = 0; j < numFilesToCreate; j++)
            {
                filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j));
                repeatedLine = String.Format("Content for Original file {0}",
                    Path.GetFileName(filename));
                TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000);
                entriesAdded++;
            }

            // Create the zip file
            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zip1 = new ZipFile())
            {
                String[] filenames = Directory.GetFiles("A");
                foreach (String f in filenames)
                    zip1.AddFile(f, "");
                zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive will be updated.";
                zip1.Save(zipFileToCreate);
            }

            // Verify the files are in the zip
            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded,
                "The Zip file has the wrong number of entries.");

            // create another subdirectory
            subdir = Path.Combine(TopLevelDir, "B");
            Directory.CreateDirectory(subdir);

            // create a bunch more files
            int newFileCount = numFilesToCreate + _rnd.Next(3) + 3;
            for (j = 0; j < newFileCount; j++)
            {
                filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j));
                repeatedLine = String.Format("Content for the updated file {0} {1}",
                    Path.GetFileName(filename),
                    System.DateTime.Now.ToString("yyyy-MM-dd"));
                TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(1000) + 2000);
                entriesAdded++;
            }

            // Update those files in the zip file
            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zip1 = FileSystemZip.Read(zipFileToCreate))
            {
                String[] filenames = Directory.GetFiles("B");
                foreach (String f in filenames)
                    zip1.UpdateItem(f, "");
                zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive has been updated.";
                zip1.Save(zipFileToCreate);
            }

            // Verify the number of files in the zip
            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), newFileCount,
                "The Zip file has the wrong number of entries.");

            // now extract the files and verify their contents
            using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate))
            {
                foreach (string s in zip3.EntryFileNames)
                {
                    repeatedLine = String.Format("Content for the updated file {0} {1}",
                        s,
                        System.DateTime.Now.ToString("yyyy-MM-dd"));
                    zip3[s].Extract("extract");

                    // verify the content of the updated file.
                    var sr = new StreamReader(Path.Combine("extract", s));
                    string sLine = sr.ReadLine();
                    sr.Close();

                    Assert.AreEqual<string>(repeatedLine, sLine,
                            String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s));
                }
            }
        }