当前位置: 首页>>代码示例>>C#>>正文


C# ZipFile.Dispose方法代码示例

本文整理汇总了C#中ZipFile.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.Dispose方法的具体用法?C# ZipFile.Dispose怎么用?C# ZipFile.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ZipFile的用法示例。


在下文中一共展示了ZipFile.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MainSuccessScenario

        public void MainSuccessScenario()
        {
            var content1 = "content1 " + Guid.NewGuid();
            var content2 = "content2 " + Guid.NewGuid();

            using (var write = new ZipFile())
            {
                write.AddFileFromString("file1.txt", "", content1);
                write.AddFileFromString("file2.txt", @"Dir1\Dir2\", content2);
                write.AddDirectoryByName("Dir2/Dir3");
                write.Save("testarc.zip");
                write.Dispose();
            }

            using(var read = new ZipFile("testarc.zip"))
            {
                Assert.AreEqual(1, read.Entries.Where(e => e.IsDirectory).Count());
                Assert.AreEqual(2, read.Entries.Where(e => !e.IsDirectory).Count());

                var ms1 = new MemoryStream();
                var ms2 = new MemoryStream();
                read.Extract(@"file1.txt", ms1);
                read.Extract(@"Dir1\Dir2\file2.txt", ms2);
                ms1.Seek(0, SeekOrigin.Begin);
                ms2.Seek(0, SeekOrigin.Begin);
                read.Dispose();

                Assert.AreEqual(content1, new StreamReader(ms1).ReadToEnd());
                Assert.AreEqual(content2, new StreamReader(ms2).ReadToEnd());
            }

            using (var write2 = new ZipFile("testarc.zip"))
            {
                write2.RemoveEntry(@"file1.txt");
                write2.Save();
                write2.Dispose();
            }

            using (var read2 = new ZipFile("testarc.zip"))
            {
                Assert.AreEqual(1, read2.Entries.Where(e => !e.IsDirectory).Count());
                Assert.AreEqual(1, read2.Entries.Where(e => e.IsDirectory).Count());
            }
        }
开发者ID:xeno-by,项目名称:datavault,代码行数:44,代码来源:ZipLibTests.cs

示例2: Launch

		///<summary>Returns true if the communications were successful, and false if they failed. If they failed, a rollback will happen automatically by deleting the previously created X12 file. The batchnum is supplied for the possible rollback.  Also used for mail retrieval.</summary>
		public static bool Launch(Clearinghouse clearhouse,int batchNum,EnumClaimMedType medType){
			string batchFile="";
			try {
				if(!Directory.Exists(clearhouse.ExportPath)) {
					throw new Exception("Clearinghouse export path is invalid.");
				}
				//We make sure to only send the X12 batch file for the current batch, so that if there is a failure, then we know
				//for sure that we need to reverse the batch. This will also help us avoid any exterraneous/old batch files in the
				//same directory which might be left if there is a permission issue when trying to delete the batch files after processing.
				batchFile=Path.Combine(clearhouse.ExportPath,"claims"+batchNum+".txt");
				//byte[] fileBytes=File.ReadAllBytes(batchFile);//unused
				MemoryStream zipMemoryStream=new MemoryStream();
				ZipFile tempZip=new ZipFile();
				tempZip.AddFile(batchFile,"");
				tempZip.Save(zipMemoryStream);
				tempZip.Dispose();
				zipMemoryStream.Position=0;
				byte[] zipFileBytes=zipMemoryStream.GetBuffer();
				string zipFileBytesBase64=Convert.ToBase64String(zipFileBytes);
				zipMemoryStream.Dispose();
				if(clearhouse.ISA15=="P") {//production interface
					string messageType="MCD";//medical
					if(medType==EnumClaimMedType.Institutional) {
						messageType="HCD";
					}
					else if(medType==EnumClaimMedType.Dental) {
						//messageType="DCD";//not used/tested yet, but planned for future.
					}
					EmdeonITS.ITSWS itsws=new EmdeonITS.ITSWS();
					itsws.Url=emdeonITSUrl;
					EmdeonITS.ITSReturn response=itsws.PutFileExt(clearhouse.LoginID,clearhouse.Password,messageType,Path.GetFileName(batchFile),zipFileBytesBase64);
					if(response.ErrorCode!=0) { //Batch submission successful.
						throw new Exception("Emdeon rejected all claims in the current batch file "+batchFile+". Error number from Emdeon: "+response.ErrorCode+". Error message from Emdeon: "+response.Response);
					}
				}
				else {//test interface
					string messageType="MCT";//medical
					if(medType==EnumClaimMedType.Institutional) {
						messageType="HCT";
					}
					else if(medType==EnumClaimMedType.Dental) {
						//messageType="DCT";//not used/tested yet, but planned for future.
					}
					EmdeonITSTest.ITSWS itswsTest=new EmdeonITSTest.ITSWS();
					itswsTest.Url=emdeonITSUrlTest;
					EmdeonITSTest.ITSReturn responseTest=itswsTest.PutFileExt(clearhouse.LoginID,clearhouse.Password,messageType,Path.GetFileName(batchFile),zipFileBytesBase64);
					if(responseTest.ErrorCode!=0) { //Batch submission successful.
						throw new Exception("Emdeon rejected all claims in the current batch file "+batchFile+". Error number from Emdeon: "+responseTest.ErrorCode+". Error message from Emdeon: "+responseTest.Response);
					}
				}
			}
			catch(Exception e) {
				MessageBox.Show(e.Message);
				x837Controller.Rollback(clearhouse,batchNum);
				return false;
			}
			finally {
				try {
					if(batchFile!="") {
						File.Delete(batchFile);
					}
				}
				catch {
					MessageBox.Show("Failed to remove batch file "+batchFile+". Probably due to a permission issue. Check folder permissions and manually delete.");
				}
			}
			return true;
		}
开发者ID:romeroyonatan,项目名称:opendental,代码行数:69,代码来源:EmdeonMedical.cs

示例3: SubmitBatch

		private const string emdeonServerUrl="";//TODO: Get from Emdeon!

		private static void SubmitBatch(Clearinghouse clearhouse,int batchNum){
			string[] files=Directory.GetFiles(clearhouse.ExportPath);
			for(int i=0;i<files.Length;i++){
				ZipFile zip=null;
				try{
					zip=new ZipFile();
					zip.AddFile(files[i]);
					MemoryStream ms=new MemoryStream();
					zip.Save(ms);
					string fileTextZippedBase64=Convert.ToBase64String(ms.GetBuffer());
					FileInfo fi=new FileInfo(files[i]);
					string claimXML="<?xml version=\"1.0\" ?>"
						+"<claim_submission_api xmlns=\"Emdeon_claim_submission_api\" revision=\"001\">"
							+"<authentication>"
								+"<vendor_id>"+vendorId+"</vendor_id>"
								+"<user_id>"+clearhouse.LoginID+"</user_id>"
								+"<password>"+clearhouse.Password+"</password>"
							+"</authentication>"
							+"<transaction>"
							+"<trace_id>"+batchNum+"</trace_id>"//TODO: Is this the right number to use?
							+"<trx_type>submit_claim_file_request</trx_type>"
							+"<test_mode>"+testMode+"</test_mode>"
							+"<trx_data>"
								+"<claim_file>"
									+"<file_name>"+Path.GetFileName(files[i])+"</file_name>"
									+"<file_format>DCDS2</file_format>"
									+"<file_size>"+fi.Length+"</file_size>"
									+"<file_compression>pkzip</file_compression>"
									+"<file_encoding>base64</file_encoding>"
									+"<file_data>"+fileTextZippedBase64+"</file_data>"
								+"</claim_file>"
							+"</trx_data>"
						+"</transaction>"
					+"</claim_submission_api>";
					byte[] claimXMLbytes=Encoding.UTF8.GetBytes(claimXML);
					WebClient myWebClient=new WebClient();
					myWebClient.Headers.Add("Content-Type","text/xml");
					byte[] responseBytes=myWebClient.UploadData(emdeonServerUrl,claimXMLbytes);




				}finally{
					if(zip!=null){
						zip.Dispose();
					}
				}
			}
		}
开发者ID:romeroyonatan,项目名称:opendental,代码行数:51,代码来源:WebMD.cs

示例4: Archivage

        public int Archivage()
        {
            int intCodeRetour = 0x00; //=== Code de retour Normalement Terminer

            //==== Periode selon la date du jour par défaut
            string strSQL = "SELECT cp.cal_no_emission FROM lg2_calen_prod cp WHERE cp.cal_dt_emission <= ADD_MONTHS(SYSDATE, :Mois_A_Conserver) ORDER BY cp.cal_dt_emission DESC";

            OracleConnection objConn = new OracleConnection(Properties.Settings.Default.CONNECTSTRING); ;
            OracleCommand objCmd = new OracleCommand(strSQL, objConn);
            OracleDataReader odr = null;

            // create a writer and open the file
            TextWriter log = new StreamWriter(".\\logs\\DV1L3001_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".log");

            try
            {

                // write a line of text to the file
                log.WriteLine(DateTime.Now.ToString() + "==== DEBUT DU TRAITEMENT");
                log.WriteLine(DateTime.Now + " _sourceFolder = " + _sourceFolder);
                log.WriteLine(DateTime.Now + " _backupFolder = " + _backupFolder);
                log.WriteLine(DateTime.Now + " _nbMoisAConserver = " + _nbMoisAConserver);

                #region Validation des informations
                string msgErreur = "";
                //=== On vérifie si répertoire de destination existe
                if (!Directory.Exists(_sourceFolder))
                {
                    msgErreur += "Le répertoire source est inexistant. [source_folder = " + _sourceFolder + "]<BR>";
                }
                if (!Directory.Exists(_backupFolder))
                {
                    msgErreur += "Le répertoire de sauvegarde est inexistant à l'endroit spécifié. [backup_destination_folder = " + _backupFolder + "]<BR>";
                }

                if (msgErreur != "")
                {
                    log.WriteLine(DateTime.Now + " ERROR : " + msgErreur.ToString());
                    throw new ApplicationException(msgErreur);
                }
                #endregion

                objConn.Open();
                //==== On soustrait les mois pour trouver la date de départ
                objCmd.Parameters.Add("Mois_A_Conserver", OracleDbType.Varchar2).Value = _nbMoisAConserver * -1;

                odr = objCmd.ExecuteReader(CommandBehavior.CloseConnection);

                long noEmission = 0;
                if (odr.Read())
                {
                    noEmission = _noEmissionBase + (int)odr["cal_no_emission"];
                    log.WriteLine(DateTime.Now + " Start with noEmission = " + noEmission.ToString());
                }
                else
                {
                    log.WriteLine(DateTime.Now + " Start with noEmission = AUCUNE ÉMISSION");
                }

                int nbMissingFolders = 0;
                for (long i = noEmission; i >= _noEmissionBase; i--)
                {
                    //=== Si le folder existe on le zip
                    string archiveFolder = _sourceFolder + "\\" + i.ToString();

                    if (Directory.Exists(archiveFolder))
                    {
                        nbMissingFolders = 0;
                        log.WriteLine(DateTime.Now + " FOLDER EXIST archiveFolder = " + archiveFolder.ToString());
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.UpdateDirectory(archiveFolder);//==== Répertoire qui sera compressé
                            zip.Save(_backupFolder + "\\" + i.ToString() + ".zip");  //=== Nom et emplacement du fichier ZIP
                            log.WriteLine(DateTime.Now + " ZIP TO : " + _backupFolder + "\\" + i.ToString() + ".zip");
                            zip.Dispose();
                        }
                        Directory.Delete(archiveFolder, true); //==== Supprime le répertoire qui a été compressé
                        log.WriteLine(DateTime.Now + " DELETE UNCOMPRESSED FOLDER : " + archiveFolder.ToString());
                    }
                    else
                    {
                        nbMissingFolders++; //=== Cumule le nombre de répertoire manquan
                        log.WriteLine(DateTime.Now + " _" + nbMissingFolders + "_ FOLDER DOESNT EXIST archiveFolder = " + archiveFolder.ToString());

                        if (nbMissingFolders >= _maxNbMissingFolder)//=== Si 5 répertoire consécutif n'existe pas on arrete le traitement.
                        {
                            log.WriteLine(DateTime.Now + " STOP CAUSE BY MORE THEN " + _maxNbMissingFolder.ToString() + " MISSING FOLDERS");
                            break;
                        }

                    }
                }

                log.WriteLine(DateTime.Now.ToString() + "==== FIN DU TRAITEMENT");

            }
            catch (Exception ex)
            {
                //=== Envoie de courriel sur erreur
                intCodeRetour = _codeRetourErreur;
//.........这里部分代码省略.........
开发者ID:judgeprophet,项目名称:DV1L3001_ArchivageFichiersRdi,代码行数:101,代码来源:ArchivageRDI.cs

示例5: DoCollect


//.........这里部分代码省略.........

            //---------------------------------
            //          BUILD ZIP NAME
            //---------------------------------
            ZipFileName = Collect.BuildZipName(TotalFindingsCount);
            ZipFile zip = new ZipFile(ZipFileName);

            if (AgentSettings.ContainsKey("Reporting_Archive_Password"))
            {
                IntPtr pptr = IntPtr.Zero;
                //do this secure string thing if password specified
                char[] str = AgentSettings["Reporting_Archive_Password"].ToCharArray();

                fixed (char* pChars = str)
                {
                    ZipPassword = new SecureString(pChars, str.Length);
                }

                //decrypt our password in memory
                pptr = Marshal.SecureStringToBSTR(ZipPassword);
                zip.Password = Marshal.PtrToStringBSTR(pptr);

                //zero the password memory
                Marshal.ZeroFreeBSTR(pptr);
            }

            zip.TempFileFolder = ".";
            ArrayList CollectList = new ArrayList();
            int count = 0;

            AgentScanLog.AppendLine("COLLECT:  Searching file signature matches for files...");

            //loop through file signatures
            foreach (CwXML.FileSignatureMatch fileMatch in AgentSignatureMatches.FileSignatureMatches)
                if (Collect.AddToZip(zip, fileMatch.FullPath))
                    count++;

            AgentScanLog.AppendLine("COLLECT:  Added " + count + " files.");
            count = 0;
            AgentScanLog.AppendLine("COLLECT:  Searching registry signature matches for files...");

            //loop through registry signatures
            foreach (CwXML.RegistrySignatureMatch registryMatch in AgentSignatureMatches.RegistrySignatureMatches)
                if (registryMatch.IsFileOnDisk)
                    if (Collect.AddToZip(zip, registryMatch.RegistryValueData))
                        count++;

            AgentScanLog.AppendLine("COLLECT:  Added " + count + " files.");
            AgentScanLog.AppendLine("COLLECT:  Generating infection summary report...");

            //---------------------------------
            //          ADD INFECTION LOG
            //---------------------------------
            //2.  infection log (Infection_Log.txt) which we create
            StreamWriter infectionlog = new StreamWriter("InfectionLog.txt");
            StringBuilder InfectionSummaryReport = new StringBuilder();

            //print infection summary for each signature type
            RegistryHelper RegHelper = new RegistryHelper();
            FileHelper FileHelper = new FileHelper();
            MemoryHelper MemHelper = new MemoryHelper();
            RegHelper.PrintRegistryFindings(AgentSignatureMatches.RegistrySignatureMatches, ref InfectionSummaryReport);
            FileHelper.PrintFileFindings(AgentSignatureMatches.FileSignatureMatches, ref InfectionSummaryReport);
            MemHelper.PrintMemoryFindings(AgentSignatureMatches.MemorySignatureMatches, ref InfectionSummaryReport);
            infectionlog.WriteLine(InfectionSummaryReport.ToString());
            infectionlog.Close();
            zip.AddFile("InfectionLog.txt");

            AgentScanLog.AppendLine("COLLECT:  Enumerating USB Devices...");

            //---------------------------------
            //          ADD USB DEVICES LOG
            //---------------------------------
            //3.  usb device list file (USB_Devices.txt) which we create
            StreamWriter usblogfile = new StreamWriter("USB_Devices.txt");
            StringBuilder UsbDevicesReport = new StringBuilder();
            Collect.EnumerateUSBDevices(ref UsbDevicesReport);
            usblogfile.WriteLine(UsbDevicesReport.ToString());
            usblogfile.Close();
            zip.AddFile("USB_Devices.txt");

            //---------------------------------
            //          ADD .NET LOG
            //---------------------------------
            //4.  .net installation log (if exists)
            try
            {
                FileInfo dotnetfxLogfile = new FileInfo("dotnetfx_install_log.txt");
                if (dotnetfxLogfile.Exists)
                    zip.AddFile("dotnetfx_install_log.txt");
            }
            catch { } //no biggie..

            AgentScanLog.AppendLine("COLLECT:  All evidence collected.");
            AgentScanLog.AppendLine("COLLECT:  Saving zip to disk...");
            zip.Save();
            zip.Dispose();  //at this point zip is closed and written to disk

            return true;
        }
开发者ID:kumaraguruv,项目名称:codeword,代码行数:101,代码来源:AgentScanner.cs

示例6: ConvertConfiguration

		public void ConvertConfiguration()
		{
			if (FiresecManager.FiresecDriver == null)
				return;

			if (MessageBoxService.ShowQuestion("Вы уверены, что хотите конвертировать конфигурацию?") == MessageBoxResult.Yes)
			{
				WaitHelper.Execute(() =>
				{
					LoadingService.Show("Конвертирование конфигурации", "Конвертирование конфигурации", 6);
					var convertationResult = FiresecManager.FiresecDriver.Convert();
					if (convertationResult.HasError)
					{
						MessageBoxService.ShowError(convertationResult.Error);
						return;
					}
                    LoadingService.Show("Синхронизация конфигурации", "Конвертирование конфигурации", 6);
                    FiresecManager.FiresecDriver.Synchronyze(false);

					ServiceFactory.SaveService.FSChanged = false;
					ServiceFactory.SaveService.PlansChanged = false;
					LoadingService.DoStep("Обновление конфигурации");
					FiresecManager.UpdateConfiguration();

					LoadingService.DoStep("Сохранение конфигурации");
					var tempFolderName = AppDataFolderHelper.GetTempFolder();
					if (!Directory.Exists(tempFolderName))
						Directory.CreateDirectory(tempFolderName);

					var tempFileName = AppDataFolderHelper.GetTempFileName();
					if (File.Exists(tempFileName))
						File.Delete(tempFileName);

					TempZipConfigurationItemsCollection = new ZipConfigurationItemsCollection();

					AddConfiguration(tempFolderName, "DeviceConfiguration.xml", FiresecManager.FiresecConfiguration.DeviceConfiguration, 1, 1);
					AddConfiguration(tempFolderName, "PlansConfiguration.xml", FiresecManager.PlansConfiguration, 1, 1);
					AddConfiguration(tempFolderName, "ZipConfigurationItemsCollection.xml", TempZipConfigurationItemsCollection, 1, 1);

					var destinationImagesDirectory = AppDataFolderHelper.GetFolder(Path.Combine(tempFolderName, "Content"));
					if (Directory.Exists(ServiceFactory.ContentService.ContentFolder))
					{
						if (Directory.Exists(destinationImagesDirectory))
							Directory.Delete(destinationImagesDirectory);
						if (!Directory.Exists(destinationImagesDirectory))
							Directory.CreateDirectory(destinationImagesDirectory);
						var sourceImagesDirectoryInfo = new DirectoryInfo(ServiceFactory.ContentService.ContentFolder);
						foreach (var fileInfo in sourceImagesDirectoryInfo.GetFiles())
						{
							fileInfo.CopyTo(Path.Combine(destinationImagesDirectory, fileInfo.Name));
						}
					}

					var zipFile = new ZipFile(tempFileName);
					zipFile.AddDirectory(tempFolderName);
					zipFile.Save(tempFileName);
					zipFile.Dispose();
					if (Directory.Exists(tempFolderName))
						Directory.Delete(tempFolderName, true);

					if (Directory.Exists(tempFolderName))
						Directory.Delete(tempFolderName, true);

					using (var fileStream = new FileStream(tempFileName, FileMode.Open))
					{
						FiresecManager.FiresecService.SetConfig(fileStream);
					}
					File.Delete(tempFileName);

					LoadingService.DoStep("Оповещение клиентов об изменении конфигурации");
					FiresecManager.FiresecService.NotifyClientsOnConfigurationChanged();
					LoadingService.Close();
				});
				ServiceFactory.Events.GetEvent<ConfigurationChangedEvent>().Publish(null);
			}
		}
开发者ID:saeednazari,项目名称:Rubezh,代码行数:76,代码来源:FS1ConvertationHelper.cs

示例7: Initialize

    public static void Initialize()
    {
        if (!File.Exists(websitePath + "\\Resources"))
        {

            ZipFile myfile = new ZipFile();

            //Create base directory structure for Zip file
            myfile.AddDirectoryByName("Webpages");

            myfile.Save(websitePath+"\\Resources");
            myfile.Dispose();

        }

        basefile = ZipFile.Read(websitePath+"\\Resources");
    }
开发者ID:BGCX262,项目名称:zuneusermarketplace-svn-to-git,代码行数:17,代码来源:WebComponents.cs

示例8: ReceivedOCR_MASTER


//.........这里部分代码省略.........
                            // Error with logger
                        }
                    }
                }   // <== Add Manifest(s) to Case
                catch (System.NullReferenceException)
                {
                    // Container Object was not created after
                    // deserializing object. Don't worry about it,
                    // press on.
                }

                try
                {   // ==> Add per-container OCR file(s) to case
                    for (int id = 0; id < master_msg.body.payload.Cont.Length; id++)
                    {
                        try
                        {
                            if (File.Exists(master_msg.body.payload.Cont[id].FileName))
                            {
                                string basePath = @"C:\Temp\";
                                if (master_msg.body.payload.Cont[id].FileName.EndsWith(".zip", false, null))
                                {
                                    ZipFile zf = new ZipFile(master_msg.body.payload.Cont[id].FileName);

                                    foreach(ZipEntry ze in zf)
                                    {
                                        if (ze.FileName.EndsWith(".jpg", false, null))
                                        {
                                            ze.Extract(basePath);
                                            m_cargoHostIF.AddOCRFile(rootCaseID[id], basePath + ze.FileName);
                                        }
                                    }

                                    zf.Dispose();
                                }
                                else
                                {
                                    m_cargoHostIF.AddOCRFile(rootCaseID[id], master_msg.body.payload.Cont[id].FileName);
                                }
                            }
                        }
                        catch (System.NullReferenceException)
                        {
                            // Container Object was not created after
                            // deserializing object. Don't worry about
                            // it, press on.
                        }
                        catch (CargoException)
                        {
                            // Error with logger
                        }
                    }
                }   // <== Add per-container OCR file(s) to case
                catch (System.NullReferenceException)
                {
                    // Container Object was not created after
                    // deserializing object. Don't worry about it, press
                    // on.
                }

                try
                {   // ==> Add per-trailer OCR file(s) to case
                    for (int id = 0; id < master_msg.body.payload.Trailer.Length; id++)
                    {
                        try
                        {
开发者ID:BdGL3,项目名称:CXPortal,代码行数:67,代码来源:frmOcrSnmMonitor.cs

示例9: unzip

        private void unzip(string zipFile, string extractFolder)
        {
            try
            {
                using (zip = ZipFile.Read(zipFile))
                {
                    double step = (100 / zip.Count);
                    double percentComplete = 0;
                    int realPercentComplete = 0;
                    foreach (ZipEntry file in zip)
                    {
                        try
                        {
                            System.Threading.Thread.Sleep(10);
                            file.Extract(extractFolder, ExtractExistingFileAction.OverwriteSilently);
                        }
                        catch (IOException e)
                        {

                            //file.Extract(extractFolder, ExtractExistingFileAction.OverwriteSilently);
                            //e.Message;
                            //File.Delete()
                        }
                            percentComplete = percentComplete + step;
                            realPercentComplete = (int)percentComplete;
                            backgroundWorker1.ReportProgress(realPercentComplete);
                    }
                    zip.Dispose();
                }
            }
            catch (ZipException)
                {
                    MessageBox.Show("Error Downloading, please try again. If this is not the first\ntime you have seen this, tell Willster he messed up");
                }
        }
开发者ID:Willster419,项目名称:RelicModManager,代码行数:35,代码来源:MainWindow.cs

示例10: SaveImpl

        private void SaveImpl(String fileName, bool rebuildZipEntries)
        {
            using (ExposeReadOnly())
            {
                var newzip = new ZipFile(){Encoding = Encoding.UTF8};

                // bug. here we face a potential tho very unprobable sync problem
                // if we've imported some nodes from another vault and are now unbinding them
                // it's possible that the vault will right now undergo certain changes that
                // won't be propagated to the nodes we've just unbound
                Root.GetValuesRecursive(ValueKind.RegularAndInternal).ForEach(Bind);
                Root.GetBranchesRecursive().ForEach(Bind);

                // mapping between values/branches and entries in the new file
                var newZeIndex = new Dictionary<IElement, String>();

                // save all values -> this will also automatically create corresponding branches
                foreach (Value value in Root.GetValuesRecursive(ValueKind.RegularAndInternal))
                {
                    var contentStream = value.ContentStream.FixupForBeingSaved();
                    var valueZe = newzip.AddFileStream(value.Name, value.VPath.Parent.ToZipPathDir(), contentStream);
                    newZeIndex.Add(value, valueZe.FileName);

                    if (value.Metadata.Raw != null)
                        newzip.AddFileStream(value.Name + "$", value.VPath.Parent.ToZipPathDir(), value.Metadata.Raw.AsStream());
                }

                // despite of the previous step having created the branches, 
                // we still need to explicitly add them in order to store the metadata
                foreach(Branch branch in Root.GetBranchesRecursive())
                {
                    var branchZe = newzip.AddDirectoryByName(branch.VPath.ToZipPathDir());
                    newZeIndex.Add(branch, branchZe.FileName);

                    if (branch.Metadata.Raw != null)
                        newzip.AddFileStream("$", branch.VPath.ToZipPathDir(), branch.Metadata.Raw.AsStream());
                }

                // root metadata requires special treatment since root doesn't get enumerated
                if (Root.Metadata.Raw.IsNeitherNullNorEmpty())
                    newzip.AddFileStream("$", String.Empty.ToZipPathDir(), Root.Metadata.Raw.AsStream());

                if (rebuildZipEntries)
                {
                    GC.Collect(); // is this really necessary here?
                    var deletedButStillAlive = BoundElements.Select(wr => wr.IsAlive ? (IElement)wr.Target : null)
                        .Where(el => el != null)
                        .Except(Root.GetValuesRecursive(ValueKind.RegularAndInternal).Cast<IElement>())
                        .Except(Root.GetBranchesRecursive().Cast<IElement>())
                        .Except(Root.MkArray())
                        .Distinct();

                    // fixup metadata/content streams of deleted and not yet gcollected nodes
                    Action<Action> neverFail = a => { try { a(); } catch { /* just ignore */ } };
                    deletedButStillAlive.ForEach(el => neverFail(() => el.CacheInMemory()));

                    // only now can we dispose the previous zip instance
                    // previously it was necessary to extract streams we're going to repack
                    if (Zip != null)
                    {
                        Zip.Dispose();
                    }

                    Zip = newzip;
                    newzip.Save(fileName);

                    // fixup content/metadata streams to reference the new file/vpaths
                    var opt = Zip.Entries.ToDictionary(ze => ze.FileName, ze => ze);
                    foreach (Value value in Root.GetValuesRecursive(ValueKind.RegularAndInternal))
                    {
                        var contentFile = newZeIndex[value];
                        var metadataFile = contentFile + "$";

                        value.SetContent(() => opt[contentFile].ExtractEager());
                        value.RawSetMetadata(() => opt.GetOrDefault(metadataFile).ExtractEager());
                    }

                    foreach (Branch branch in Root.GetBranchesRecursive())
                    {
                        var metadataFile = newZeIndex[branch] + "$";
                        branch.RawSetMetadata(() => opt.GetOrDefault(metadataFile).ExtractEager());
                    }

                    // root metadata requires special treatment since root doesn't get enumerated
                    Root.RawSetMetadata(() => (opt.GetOrDefault("/$") ?? opt.GetOrDefault("$")).ExtractEager());

                    // set the changes in stone
                    Root.AfterSave();
                    Root.GetBranchesRecursive().Cast<Branch>().ForEach(b => b.AfterSave());
                    Root.GetValuesRecursive(ValueKind.RegularAndInternal).Cast<Value>().ForEach(v => v.AfterSave());
                }
                else
                {
                    if (Uri == fileName)
                    {
                        throw new InvalidOperationException("Saving vault into its source file requires rebuilding ZIP entries.");
                    }
                    else
                    {
                        newzip.Save(fileName);
//.........这里部分代码省略.........
开发者ID:xeno-by,项目名称:datavault,代码行数:101,代码来源:ZipVault.cs


注:本文中的ZipFile.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。