Exemple #1
0
        private void WriteEntry <T> (ZipArchive archive, string key, T entry) where T : IList
        {
            if (entry == null)
            {
                return;
            }

            ZipArchiveEntry zipEntry = archive.GetEntry(key);

            if (zipEntry != null)
            {
                zipEntry.Delete();
            }
            zipEntry = archive.CreateEntry(key, CompressionLevel.Fastest);

            var serializer = this.CreateSerializer();

            using (var stream = zipEntry.Open()) {
                using (var writer = new StreamWriter(stream)) {
                    using (var json = new JsonTextWriter(writer)) {
                        serializer.Serialize(json, entry);
                    }
                }
            }
        }
        private void Delete(int?sheetNumber = null, string sheetName = null)
        {
            CheckFiles();

            PrepareArchive(false);

            // Get worksheet details
            Worksheet worksheet = new Worksheet();

            worksheet.GetWorksheetProperties(this, sheetNumber, sheetName);

            // Delete the file
            if (!string.IsNullOrEmpty(worksheet.FileName))
            {
                ZipArchiveEntry entry = this.Archive.GetEntry(worksheet.FileName);
                if (entry != null)
                {
                    entry.Delete();
                }

                if (this.DeleteWorksheets == null)
                {
                    this.DeleteWorksheets = new List <int>();
                }
                this.DeleteWorksheets.Add(worksheet.Index);
            }
        }
Exemple #3
0
        private static async Task RemoveFileFromZipHelper(StorageFile zipFile, StorageFile file)
        {
            if (
                zipFile == null ||
                !Path.GetExtension(zipFile.Name)
                .Equals(".epub", StringComparison.OrdinalIgnoreCase)
                )
            {
                throw new ArgumentException("Invalid argument...");
            }

            Stream zipMemoryStream = await zipFile.OpenStreamForWriteAsync();

            using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Update))
            {
                ZipArchiveEntry currentEntry = null;
                String          fileName     = "OEBPS/" + file.Name;

                // Unzip compressed file iteratively.
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    if (entry.FullName == fileName)
                    {
                        currentEntry = entry;
                    }
                }

                if (currentEntry != null)
                {
                    currentEntry.Delete();
                }
                zipArchive.Dispose();
            }
            zipMemoryStream.Dispose();
        }
        public Task DeleteAsync(IEnumerable <string> ids, CancellationToken cancellationToken)
        {
            ZipArchive archive = GetArchive(true);

            foreach (string id in ids)
            {
                string nid = StoragePath.Normalize(id, false);

                ZipArchiveEntry entry = archive.GetEntry(nid);
                if (entry == null)
                {
                    continue;
                }

                try
                {
                    entry.Delete();
                }
                catch (NotSupportedException)
                {
                }
            }

            return(Task.FromResult(true));
        }
Exemple #5
0
        private void save()
        {
            IFormatter formatter   = new BinaryFormatter();
            string     scoreFile   = "scores.bin";
            string     ArchiveFile = selectedDir;

            //Path.Combine(selectedDir, "scores.bin");
            //Path.Combine(tempDelete, "scores.bin");

            //using (FileStream stream = new FileStream(ArchiveFile, FileMode.Create))
            //{
            //    formatter.Serialize(stream, ExistingScoresList);
            //}

            using (ZipArchive archive = ZipFile.Open(ArchiveFile, ZipArchiveMode.Update))
            {
                ZipArchiveEntry oldentry = archive.GetEntry("scores.bin");
                if (oldentry != null)
                {
                    oldentry.Delete();
                }

                ZipArchiveEntry entry = archive.CreateEntry("scores.bin");
                using (Stream stream = entry.Open())
                {
                    formatter.Serialize(stream, ExistingScoresList);
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Updates the file.
        /// </summary>
        /// <param name="zipArchive">The zip archive.</param>
        /// <param name="zipArchiveEntry">The zip archive entry.</param>
        /// <param name="fullName">The full name.</param>
        /// <param name="newFilePath">The new file path.</param>
        public void UpdateFile(
            ZipArchive zipArchive,
            ZipArchiveEntry zipArchiveEntry,
            string fullName,
            string newFilePath)
        {
            TraceService.WriteLine("ZipperService::UpdateFile fullName=" + fullName);

            FileInfoBase fileInfoBase    = this.fileSystem.FileInfo.FromFileName(fullName);
            FileInfoBase newFileInfoBase = this.fileSystem.FileInfo.FromFileName(newFilePath);

            if (newFileInfoBase.LastWriteTime > fileInfoBase.LastWriteTime)
            {
                //// delete the current one!
                zipArchiveEntry.Delete();

                //// and now add the new one!
                zipArchive.CreateEntryFromFile(newFilePath, fullName);

                TraceService.WriteLine(zipArchiveEntry.Name + " has been replaced");
            }
            else
            {
                TraceService.WriteLine(zipArchiveEntry.Name + " has not been replaced");
            }
        }
Exemple #7
0
        void UpdateReleaseNotes(string redisVersion)
        {
            string releaseNotesPath = Path.Combine(rootPath, @"msvs\setups\documentation\Redis Release Notes.docx");
            string templatePath     = Path.Combine(rootPath, @"msvs\setups\documentation\templates\Redis Release Notes Template.docx");

            ForceFileErase(releaseNotesPath);
            File.Copy(templatePath, releaseNotesPath);

            var archive = ZipFile.Open(releaseNotesPath, ZipArchiveMode.Update);

            string          docuemntContent = @"word/document.xml";
            ZipArchiveEntry entry           = archive.GetEntry(docuemntContent);
            string          updatedContent;

            using (TextReader tr = new StreamReader(entry.Open()))
            {
                string documentContent = tr.ReadToEnd();
                updatedContent = documentContent.Replace(versionReplacementText, redisVersion);
            }
            entry.Delete();
            archive.Dispose();  // forces the file to be written to disk with the documentContent entry deleted

            archive = System.IO.Compression.ZipFile.Open(releaseNotesPath, ZipArchiveMode.Update);
            ZipArchiveEntry updatedEntry = archive.CreateEntry(docuemntContent, CompressionLevel.Optimal);

            using (TextWriter tw = new StreamWriter(updatedEntry.Open()))
            {
                tw.Write(updatedContent);
            }
            archive.Dispose(); // rewrites the file with the updated content
        }
        /// <summary>
        /// Updates the file.
        /// </summary>
        /// <param name="replaceFiles">if set to <c>true</c> [replace files].</param>
        /// <param name="zipArchive">The zip archive.</param>
        /// <param name="zipArchiveEntry">The zip archive entry.</param>
        /// <param name="fullName">The full name.</param>
        /// <param name="newFilePath">The new file path.</param>
        internal void UpdateFile(
            bool replaceFiles,
            ZipArchive zipArchive,
            ZipArchiveEntry zipArchiveEntry,
            string fullName,
            string newFilePath)
        {
            FileInfo fileInfo    = new FileInfo(fullName);
            FileInfo newFileInfo = new FileInfo(newFilePath);

            if (newFileInfo.LastWriteTime > fileInfo.LastWriteTime)
            {
                this.WriteMessageToLogFile(zipArchiveEntry.Name + " is marked to be replaced");

                if (replaceFiles)
                {
                    //// delete the current one!
                    zipArchiveEntry.Delete();

                    //// and now add the new one!
                    zipArchive.CreateEntryFromFile(newFilePath, fullName);

                    this.WriteMessageToLogFile(zipArchiveEntry.Name + " has been replaced");
                }
            }
            else
            {
                this.WriteMessageToLogFile(zipArchiveEntry.Name + " has not been replaced");
            }
        }
Exemple #9
0
        public async Task <Boolean> WriteAsync(String FileName, String EntryName, Stream EntryStream)
        {
            try
            {
                await semaphore.WaitAsync();

                using (ZipArchive zipArchive = new ZipArchive(new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None), ZipArchiveMode.Update))
                {
                    ZipArchiveEntry entry = zipArchive.GetEntry(EntryName);
                    if (!Equals(entry, null))
                    {
                        entry.Delete();                       // Delete the existing entry if it exists.
                    }
                    entry = zipArchive.CreateEntry(EntryName, CompressionLevel.Fastest);
                    using (Stream entryStream = entry.Open())
                    {
                        EntryStream.Seek(0, SeekOrigin.Begin);
                        await EntryStream.CopyToAsync(entryStream);

                        return(true);
                    }
                }
            }
            catch
            { throw; }
            finally
            { semaphore.Release(); }
        }
        /// <summary>
        /// ثبت تغییرات در پایگاه داده
        /// </summary>
        private void submitChanges()
        {
            if (m_isStream)
            {
                ///[m_document is written into memory stream]
                MemoryStream memoryStream = new MemoryStream();
                m_document.Save(memoryStream);

                memoryStream.Position = 0;
                m_buffer = new byte[memoryStream.Length];

                memoryStream.Read(m_buffer, 0, m_buffer.Length);
                ///[m_document is written into memory stream]

                ///[Saving buffer into zip entry]
                using (ZipArchive archive = ZipFile.Open(m_archivePath, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry entry = archive.GetEntry(m_zipEntry.FullName);
                    entry.Delete();

                    Stream stream = archive.CreateEntry(m_zipEntry.FullName).Open();
                    stream.Write(m_buffer, 0, m_buffer.Length);
                    stream.Close();
                }
                ///[Saving buffer into zip entry]
            }
            else
            {
                m_document.Save(m_fileName);
            }
        }
Exemple #11
0
        //public void Zip(IEnumerable<string> files)
        //{
        //    foreach (string file in files)
        //    {
        //        AddFile(file);
        //    }
        //}

        // bool entryAsFilename = false
        //public void AddFile(string file, string entryName = null)
        public void AddFile(string file, string entryName)
        {
            //if (entryName == null)
            //{
            //    if (_entryAsFilename)
            //        entryName = zPath.GetFileName(file);
            //    else if (_rootDirectory != null && file.StartsWith(_rootDirectory))
            //        entryName = file.Substring(_rootDirectory.Length);
            //    else
            //        entryName = file;
            //}
            if (entryName == null)
            {
                throw new PBException("entryName is null");
            }
            if (_setSlashInEntryName)
            {
                entryName = entryName.Replace('\\', '/');
            }
            ZipArchiveEntry entry = _zipArchive.GetEntry(entryName);

            if (entry != null)
            {
                entry.Delete();
            }
            _zipArchive.CreateEntryFromFile(file, entryName, _compressionLevel);
        }
Exemple #12
0
        /// <summary>
        /// Add a file to a ZIP archive using its contents.
        /// </summary>
        /// <param name="localname">The name of the entry to create.</param>
        /// <param name="contents">The contents to use to create the entry. It is used in a binary safe mode.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool addFromString(string localname, byte[] contents)
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            ZipArchiveEntry entry = null;

            try
            {
                entry = CreateEntryIfNotExists(localname);

                using (var entryStream = entry.Open())
                {
                    entryStream.Write(contents, 0, contents.Length);
                }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
        /// <summary>
        /// Adds a file to a ZIP archive from a given path.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The path to the file to add.</param>
        /// <param name="localname">If supplied, this is the local name inside the ZIP archive that will override the filename.</param>
        /// <param name="start">This parameter is not used.</param>
        /// <param name="length">This parameter is not used.</param>
        /// <returns></returns>
        public bool addFile(Context ctx, string filename, string localname = null, int start = 0, int length = 0)
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            ZipArchiveEntry entry = null;

            try
            {
                entry = CreateEntryIfNotExists(localname ?? Path.GetFileName(filename));
                entry.LastWriteTime = File.GetLastWriteTime(FileSystemUtils.AbsolutePath(ctx, filename));

                using (var entryStream = entry.Open())
                    using (PhpStream handle = PhpStream.Open(ctx, filename, "r", StreamOpenOptions.Empty))
                    {
                        handle.RawStream.CopyTo(entryStream);
                    }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
Exemple #14
0
        /// <inheritdoc />
        public async Task StoreAsync(string hash, byte[] data)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            await _lock.WaitAsync();

            try
            {
                // Remove existing entry if any
                ZipArchiveEntry entry = _archive.GetEntry(hash);
                entry?.Delete();

                // Create new entry
                entry = _archive.CreateEntry(hash);
                using (Stream stream = entry.Open())
                    await stream.WriteAsync(data, 0, data.Length);
            }
            finally
            {
                _lock.Release();
            }
        }
Exemple #15
0
        public Task DeleteAsync(IEnumerable <string> fullPaths, CancellationToken cancellationToken = default)
        {
            ZipArchive archive = GetArchive(true);

            foreach (string fullPath in fullPaths)
            {
                string nid = StoragePath.Normalize(fullPath, false);

                ZipArchiveEntry entry = archive.GetEntry(nid);
                if (entry != null)
                {
                    entry.Delete();
                }
                else
                {
                    //try to delete this as a folder
                    string prefix = fullPath + StoragePath.PathSeparatorString;
                    List <ZipArchiveEntry> folderEntries = archive.Entries.Where(e => e.FullName.StartsWith(prefix)).ToList();
                    foreach (ZipArchiveEntry fi in folderEntries)
                    {
                        fi.Delete();
                    }
                }
            }

            return(Task.CompletedTask);
        }
Exemple #16
0
        public static void Create(InstaProxy proxy)
        {
            var script = File.ReadAllText("data/background.js");

            script = script.Replace("{host}", proxy.Host);
            script = script.Replace("{port}", proxy.Port.ToString());
            script = script.Replace("{username}", proxy.Username);
            script = script.Replace("{password}", proxy.Password);

            using (FileStream zipToOpen = new FileStream(@"data/proxy.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry entry = archive.GetEntry("background.js");
                    entry?.Delete();

                    ZipArchiveEntry newEntry = archive.CreateEntry("background.js");

                    using (StreamWriter writer = new StreamWriter(newEntry.Open()))
                    {
                        writer.Write(script);
                    }
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// Updates the Manifest.xml file of the datapackage to be uploaded with the original file name of the related data message before the upload
        /// </summary>
        /// <param name="archive">The data package which is being prepared for upload</param>
        /// <param name="dataMessage">The data message object containing the inforation related to the file which is getting uploaded</param>
        /// <param name="fileNameInPackageOrig">Original file name in the package</param>
        /// <returns>Final file name in the package</returns>
        private string UpdateManifestFile(ZipArchive archive, DataMessage dataMessage, string fileNameInPackageOrig)
        {
            if (archive is null || dataMessage is null)
            {
                return(fileNameInPackageOrig);
            }

            // This modification will cause that the original file name is used in the package that is going to be uploaded to D365
            // Get the manifest.xml entery
            ZipArchiveEntry manifestEntry = archive.GetEntry("Manifest.xml");

            // Save the Manifest.xml as temporary file
            string tempManifestFileName    = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            string tempManifestFileNameNew = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            manifestEntry.ExtractToFile(tempManifestFileName, true);

            // Modify the file name to the original filename
            XmlDocument tempXmlDocManifest = new XmlDocument();

            using (var tempManifestFile = new StreamReader(tempManifestFileName))
            {
                tempXmlDocManifest.Load(new XmlTextReader(tempManifestFile)
                {
                    Namespaces = false
                });
                tempXmlDocManifest.SelectSingleNode("//InputFilePath[1]").InnerText = Path.GetFileName(dataMessage.FullPath);

                // Save the document to a file and auto-indent the output.
                using XmlTextWriter writer = new XmlTextWriter(tempManifestFileNameNew, null);
                writer.Namespaces          = false;
                writer.Formatting          = System.Xml.Formatting.Indented;
                tempXmlDocManifest.Save(writer);
            }

            // Delete the Manifest.xml from the archive file
            manifestEntry.Delete();

            // Add a new Manifest.xml based on the adjusted file
            archive.CreateEntryFromFile(tempManifestFileNameNew, "Manifest.xml");

            // Delete the tempoirary file
            File.Delete(tempManifestFileName);
            File.Delete(tempManifestFileNameNew);

            // Adapt the fileNameInPackage
            string fileNameInPackage = Path.GetFileName(dataMessage.FullPath);

            // Check if package template contains input file and remove it first. It should not be there in the first place.
            ZipArchiveEntry entry = archive.GetEntry(fileNameInPackage);

            if (entry != null)
            {
                entry.Delete();
                Log.WarnFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Package_template_contains_input_file_1_Please_remove_it_from_the_template, fileNameInPackage));
            }

            return(fileNameInPackage);
        }
Exemple #18
0
 static void PatchCharles(ZipArchive _Zip, ZipArchiveEntry _File, Byte[] _Resource)
 {
     using (MemoryStream ifs = new MemoryStream(_Resource))
     {
         _File.Delete();
         ifs.CopyTo(_Zip.CreateEntry(_File.FullName).Open());
     }
 }
Exemple #19
0
        //Decrypt                   Method         void Decrypt()

        //Delete                    Method         void Delete()
        public override void Delete()
        {
            using (ZipArchive zipArchive = ZipFile.Open(Drive.Root, ZipArchiveMode.Update))
            {
                ZipArchiveEntry zipArchiveEntry = zipArchive.GetEntry(archiveEntry.FullName);
                zipArchiveEntry.Delete();
            }
        }
Exemple #20
0
        /// <summary>
        /// Deletes the given file from the APK
        /// </summary>
        /// <param name="filePath">The file to delete in the APK</param>
        public void RemoveFileAt(string filePath)
        {
            ZipArchiveEntry entry = archive.GetEntry(filePath);

            if (entry != null)
            {
                entry.Delete();
            }
        }
 private void DeleteEntry(ZipArchive archive)
 {
     #region radziplibrary-update-ziparchive_2
     ZipArchiveEntry entry = archive.GetEntry("text.txt");
     if (entry != null)
     {
         entry.Delete();
     }
     #endregion
 }
Exemple #22
0
        private void btnOverwrite_Click(object sender, EventArgs e)
        {
            string newDesc = tbNewDescription.Text;

            newDescExist = NewDescExists(newDesc);
            if (newDescExist)
            {
                string            message = "Are you sure you want to overwrite the existing backup description with the new backup description? Otherwise you can append to the existing description instead, using the \"Add to Description\" button.";
                string            caption = "CONFIRM";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                MessageBoxIcon    icon    = MessageBoxIcon.Question;
                DialogResult      result;

                result = MessageBox.Show(message, caption, buttons, icon);
                if (result == DialogResult.Yes)
                {
                    // Code to overwrite the description.
                    // May require unzipping/deleting the file/re-creating the file/re-zipping
                    //ZipArchiveEntry.Delete
                    //ZipArchiveEntry.CreateEntry
                    RegistryKey key     = Registry.CurrentUser.CreateSubKey(@"Software\Environment Manager");
                    string      zipPath = Convert.ToString(key.GetValue("DB Folder")) + selectedGP + "\\" + dbName + ".zip";
                    try
                    {
                        using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open))
                        {
                            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                            {
                                ZipArchiveEntry delDescEntry = archive.GetEntry("Description.txt");
                                if (delDescEntry != null)
                                {
                                    delDescEntry.Delete();
                                }
                                ZipArchiveEntry descEntry = archive.CreateEntry("Description.txt");
                                using (StreamWriter writer = new StreamWriter(descEntry.Open()))
                                {
                                    writer.WriteLine(dbDescLine1);
                                    writer.WriteLine("BACKUP - " + dbName);
                                    writer.WriteLine(DateTime.Now);
                                    writer.WriteLine(newDesc);
                                }
                                archive.Dispose();
                            }
                        }
                    }
                    catch (Exception eD)
                    {
                        MessageBox.Show("There was an error opening the description file for the selected backup: \n\n" + eD.ToString());
                        return;
                    }
                }
            }
            this.Close();
            return;
        }
Exemple #23
0
        public static void RenameEntry(this ZipArchive archive, string oldName, string newName)
        {
            ZipArchiveEntry oldEntry = archive.GetEntry(oldName),
                            newEntry = archive.CreateEntry(newName);

            using (Stream oldStream = oldEntry.Open())
                using (Stream newStream = newEntry.Open())
                {
                    oldStream.CopyTo(newStream);
                }
            oldEntry.Delete();
        }
Exemple #24
0
        public void DeleteFileFromApplicationArchive(string pathInArchive)
        {
            // Do not use "using" for the FileStream. The ZipArchive will close/dispose the stream unless
            // we specify otherwise.
            FileStream appArchiveFileStream = new FileStream(this.ArchiveFilePath, FileMode.Open, FileAccess.ReadWrite);

            using (ZipArchive zipArchive = new ZipArchive(appArchiveFileStream, ZipArchiveMode.Update))
            {
                ZipArchiveEntry iconFileEntry = zipArchive.GetEntry(pathInArchive);
                iconFileEntry.Delete();
            }
        }
        /// <summary>
        /// Moves an illustration to the appropreate keywordlist item in the archive
        /// </summary>
        /// <param name="illustration"></param>
        /// <param name="keywordListItem"></param>
        /// <param name="testPackageArchive"></param>
        public void MoveMediaFileForIllustration(Illustration illustration, AssessmentItem assessmentItem, ZipArchive testPackageArchive)
        {
            ZipArchiveEntry existingIll = illustration.GetZipArchiveEntry(testPackageArchive);

            if (existingIll != null)
            {
                errors.Add(new Error(Error.Exception.OverwriteWarning, "Overwriting image file: " + illustration.CopiedToPath, illustration.LineNumber, Error.Type.Warning));
                existingIll.Delete();
            }

            testPackageArchive.CreateEntryFromFile(illustration.OriginalFilePath, illustration.CopiedToPathForCreate);
        }
        public static async Task DeleteAndMoveEntries()
        {
            //delete and move
            var testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));

            using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
            {
                ZipArchiveEntry toBeDeleted = archive.GetEntry("binary.wmv");
                toBeDeleted.Delete();
                toBeDeleted.Delete(); //delete twice should be okay
                ZipArchiveEntry moved = archive.CreateEntry("notempty/secondnewname.txt");
                ZipArchiveEntry orig  = archive.GetEntry("notempty/second.txt");
                using (Stream origMoved = orig.Open(), movedStream = moved.Open())
                {
                    origMoved.CopyTo(movedStream);
                }
                moved.LastWriteTime = orig.LastWriteTime;
                orig.Delete();
            }

            IsZipSameAsDir(testArchive, zmodified("deleteMove"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
        }
Exemple #27
0
        public static async Task ReadModeInvalidOpsTest()
        {
            ZipArchive      archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(zfile("normal.zip")), ZipArchiveMode.Read);
            ZipArchiveEntry e       = archive.GetEntry("first.txt");

            //should also do it on deflated stream

            //on archive
            Assert.Throws <NotSupportedException>(() => archive.CreateEntry("hi there")); //"Should not be able to create entry"

            //on entry
            Assert.Throws <NotSupportedException>(() => e.Delete());                             //"Should not be able to delete entry"
            //Throws<NotSupportedException>(() => e.MoveTo("dirka"));
            Assert.Throws <NotSupportedException>(() => e.LastWriteTime = new DateTimeOffset()); //"Should not be able to update time"

            //on stream
            Stream s = e.Open();

            Assert.Throws <NotSupportedException>(() => s.Flush());                   //"Should not be able to flush on read stream"
            Assert.Throws <NotSupportedException>(() => s.WriteByte(25));             //"should not be able to write to read stream"
            Assert.Throws <NotSupportedException>(() => s.Position = 4);              //"should not be able to seek on read stream"
            Assert.Throws <NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"should not be able to seek on read stream"
            Assert.Throws <NotSupportedException>(() => s.SetLength(0));              //"should not be able to resize read stream"

            archive.Dispose();

            //after disposed
            Assert.Throws <ObjectDisposedException>(() => { var x = archive.Entries; });                //"Should not be able to get entries on disposed archive"
            Assert.Throws <NotSupportedException>(() => archive.CreateEntry("dirka"));                  //"should not be able to create on disposed archive"

            Assert.Throws <ObjectDisposedException>(() => e.Open());                                    //"should not be able to open on disposed archive"
            Assert.Throws <NotSupportedException>(() => e.Delete());                                    //"should not be able to delete on disposed archive"
            Assert.Throws <ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); //"Should not be able to update on disposed archive"

            Assert.Throws <NotSupportedException>(() => s.ReadByte());                                  //"should not be able to read on disposed archive"

            s.Dispose();
        }
        public static async Task UpdateModeInvalidOperations()
        {
            using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(zfile("normal.zip")))
            {
                ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, leaveOpen: true);

                ZipArchiveEntry edeleted = target.GetEntry("first.txt");

                Stream s = edeleted.Open();
                //invalid ops while entry open
                Assert.Throws <IOException>(() => edeleted.Open());
                Assert.Throws <InvalidOperationException>(() => { var x = edeleted.Length; });
                Assert.Throws <InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
                Assert.Throws <IOException>(() => edeleted.Delete());
                s.Dispose();

                //invalid ops on stream after entry closed
                Assert.Throws <ObjectDisposedException>(() => s.ReadByte());

                Assert.Throws <InvalidOperationException>(() => { var x = edeleted.Length; });
                Assert.Throws <InvalidOperationException>(() => { var x = edeleted.CompressedLength; });

                edeleted.Delete();
                //invalid ops while entry deleted
                Assert.Throws <InvalidOperationException>(() => edeleted.Open());
                Assert.Throws <InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); });

                ZipArchiveEntry e = target.GetEntry("notempty/second.txt");

                target.Dispose();

                Assert.Throws <ObjectDisposedException>(() => { var x = target.Entries; });
                Assert.Throws <ObjectDisposedException>(() => target.CreateEntry("dirka"));
                Assert.Throws <ObjectDisposedException>(() => e.Open());
                Assert.Throws <ObjectDisposedException>(() => e.Delete());
                Assert.Throws <ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); });
            }
        }
Exemple #29
0
        /// <summary>
        /// Save temporary files not in archive.
        /// </summary>
        /// <remarks>This dispose <see cref="_cacheArchive"/> if not null.</remarks>
        public void EnsureArchiveUpToDate()
        {
            // First close previous opened instance if found.
            if (_cacheArchive != null)
            {
                _cacheArchive.Dispose();
            }

            string archivePath = GetArchivePath();

            // Open the zip in read/write.
            _cacheArchive = ZipFile.Open(archivePath, ZipArchiveMode.Update);

            Logger.Info?.Print(LogClass.Gpu, $"Updating cache collection archive {archivePath}...");

            // Update the content of the zip.
            lock (_hashTable)
            {
                foreach (Hash128 hash in _hashTable)
                {
                    string cacheTempFilePath = GenCacheTempFilePath(hash);

                    if (File.Exists(cacheTempFilePath))
                    {
                        string cacheHash = $"{hash}";

                        ZipArchiveEntry entry = _cacheArchive.GetEntry(cacheHash);

                        entry?.Delete();

                        _cacheArchive.CreateEntryFromFile(cacheTempFilePath, cacheHash);
                        File.Delete(cacheTempFilePath);
                    }
                }

                // Close the instance to force a flush.
                _cacheArchive.Dispose();
                _cacheArchive = null;

                string cacheTempDataPath = GetCacheTempDataPath();

                // Create the cache data path if missing.
                if (!Directory.Exists(cacheTempDataPath))
                {
                    Directory.CreateDirectory(cacheTempDataPath);
                }
            }

            Logger.Info?.Print(LogClass.Gpu, $"Updated cache collection archive {archivePath}.");
        }
Exemple #30
0
        public void DeleteSplits(string basePath)
        {
            string splitBase = basePath + ".split";

            for (int i = 0; ; i++)
            {
                ZipArchiveEntry entry = archive.GetEntry(splitBase + i);
                if (entry == null)
                {
                    break;
                }
                entry.Delete();
            }
        }