Dispose() public method

public Dispose ( ) : void
return void
Beispiel #1
0
        public void FlushReopen()
        {
            linkedArchive.Dispose();
            linkedArchive = null;
            baseStream.Close();

            LinkFile(FileName);
        }
        public void AddDirectoryToArchiveIncludesDirectoryTreeInArchive()
        {
            // Arrange
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);

            var emptyDir = new Mock<DirectoryInfoBase>();
            emptyDir.SetupGet(d => d.Name).Returns("empty-dir");
            emptyDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[0]);
            var subDir = new Mock<DirectoryInfoBase>();
            subDir.SetupGet(d => d.Name).Returns("site");
            subDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { emptyDir.Object, CreateFile("home.aspx", "home content"), CreateFile("site.css", "some css") });

            var directoryInfo = new Mock<DirectoryInfoBase>();
            directoryInfo.SetupGet(f => f.Name).Returns("zip-test");
            directoryInfo.Setup(f => f.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { subDir.Object, CreateFile("zero-length-file", ""), CreateFile("log.txt", "log content") });

            // Act
            zip.AddDirectory(directoryInfo.Object, "");

            // Assert
            zip.Dispose();
            File.WriteAllBytes(@"d:\foo.zip", stream.ToArray());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(5, zip.Entries.Count);
            AssertZipEntry(zip, "log.txt", "log content");
            AssertZipEntry(zip, @"site\home.aspx", "home content");
            AssertZipEntry(zip, @"site\site.css", "some css");
            AssertZipEntry(zip, @"site\empty-dir\", null);
            AssertZipEntry(zip, @"zero-length-file", null);
        }
Beispiel #3
0
        internal void Run()
        {
            HttpListener listener = new HttpListener();
            Retry:
            string bind = "http://+:" + Config.WebService.HttpPort + string.Format("/{0}", Config.WebService.HttpSubdirectory);
            listener.Prefixes.Add(bind);
            try
            {
                listener.Start();
            }
            catch (HttpListenerException e)
            {
                if (!Versionr.Utilities.MultiArchPInvoke.IsRunningOnMono && e.NativeErrorCode == 5 && TriedToRunNetSH == false)
                {
                    // access denied - we probably need to run netsh
                    Printer.PrintError("Unable to bind web interface. Requesting access rights.");
                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo()
                    {
                        Verb = "runas",
                        FileName = "netsh",
                        Arguments = string.Format("http add urlacl url=\"{0}\" user=everyone", bind),
                        UseShellExecute = true
                    };
                    System.Diagnostics.Process ps = System.Diagnostics.Process.Start(psi);
                    ps.WaitForExit();
                    TriedToRunNetSH = true;
                    goto Retry;
                }
                throw e;
            }
            if (Config.RequiresAuthentication && !Config.AllowUnauthenticatedRead && Config.SupportsSimpleAuthentication)
                listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
            if (Config.WebService.ProvideBinaries)
            {
                System.IO.FileInfo assemblyFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                System.IO.DirectoryInfo containingDirectory = assemblyFile.Directory;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create);
                CompressFolder(containingDirectory, string.Empty, archive);
                archive.Dispose();
                Binaries = memoryStream.ToArray();
            }
            RootHandlers = new Dictionary<string, SimpleWebHandler>();
            RootHandlers.Add("/", new DirectHandler()
            {

            });
            Printer.PrintMessage("Running web interface on port #b#{0}##.", Config.WebService.HttpPort);
            while (true)
            {
                var ctx = listener.GetContext();
                Task.Run(() =>
                {
                    HandleRequest(ctx);
                });
            }
            listener.Stop();
        }
Beispiel #4
0
 public void Dispose()
 {
     //Close();
     if (_zipArchive != null)
     {
         _zipArchive.Dispose();
         _zipArchive = null;
     }
 }
Beispiel #5
0
        async public static Task ZipFolder(StorageFolder sourceFolder, StorageFolder destnFolder, string zipFileName)
        {
            StorageFile zipFile = await destnFolder.CreateFileAsync(zipFileName, CreationCollisionOption.ReplaceExisting);

            Stream zipToCreate = await zipFile.OpenStreamForWriteAsync();

            ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Update);
            await ZipFolderContents(sourceFolder, archive, sourceFolder.Path);
            archive.Dispose();
        }
Beispiel #6
0
            private async Task AsyncDecompress(string Source, string Destnation, bool IsOverwrite)
            {
                // 非同期処理
                await Task.Run(() => {
                    System.IO.Compression.ZipArchive Archive = null;

                    string FullPath = String.Empty;

                    try {
                        // ZIPアーカイブを取得
                        using (Archive = System.IO.Compression.ZipFile.Open(Source, System.IO.Compression.ZipArchiveMode.Update)) {
                            foreach (var Entry in Archive.Entries)
                            {
                                // 抽出先フルパス作成
                                FullPath = System.IO.Path.Combine(Destnation, Entry.FullName);

                                // ディレクトリかどうか。
                                if (System.String.IsNullOrEmpty(Entry.Name))
                                {
                                    // ディレクトリなら、階層を再現する。
                                    if (!System.IO.Directory.Exists(FullPath))
                                    {
                                        System.IO.Directory.CreateDirectory(FullPath);
                                    }
                                }
                                else
                                {
                                    // ファイルなら、そのまま抽出。
                                    if (IsOverwrite)
                                    {
                                        Entry.ExtractToFile(FullPath, true);
                                    }
                                    else
                                    if (!System.IO.File.Exists(FullPath))
                                    {
                                        Entry.ExtractToFile(FullPath, true);
                                    }
                                }
                            }
                        }

                        //System.IO.Compression.ZipFile.ExtractToDirectory(ArchiveFile, Directory);
                    } catch (System.Exception ex) {
                        this.MyOperator.Logger.WriteLine(ex.Message, eLogLevel.ERROR);
                    } finally{
                        Archive?.Dispose();
                    }

                    this.IsDiscompressed = true;
                }).ConfigureAwait(false);

                this.IsAsynchronous = false;
            }
		public override void Extract(string targetDirectory) {
			Logger.Debug(this, "Extracting to " + targetDirectory + "...");
			ZipArchive archive = new ZipArchive(this.Read());
			try {
				foreach(ZipArchiveEntry entry in archive.Entries) {
					if(entry.Length == 0) continue;
					this.ExtractEntry(entry, Path.Combine(targetDirectory, entry.FullName), true);
				}
			} finally {
				archive.Dispose();
			}
			Logger.Debug(this, "Extracted");
		}
Beispiel #8
0
        internal void Run()
        {
            HttpListener listener = new HttpListener();

Retry:
            string bind = "http://+:" + Config.WebService.HttpPort + string.Format("/{0}", Config.WebService.HttpSubdirectory);

            listener.Prefixes.Add(bind);
            try
            {
                listener.Start();
            }
            catch (HttpListenerException e)
            {
                if (!Versionr.Utilities.MultiArchPInvoke.IsRunningOnMono && e.NativeErrorCode == 5 && TriedToRunNetSH == false)
                {
                    Netsh.AddUrlacl(bind);
                    TriedToRunNetSH = true;
                    goto Retry;
                }
                throw e;
            }
            if (Config.RequiresAuthentication && !Config.AllowUnauthenticatedRead && Config.SupportsSimpleAuthentication)
            {
                listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
            }
            if (Config.WebService.ProvideBinaries)
            {
                System.IO.FileInfo               assemblyFile        = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                System.IO.DirectoryInfo          containingDirectory = assemblyFile.Directory;
                System.IO.MemoryStream           memoryStream        = new System.IO.MemoryStream();
                System.IO.Compression.ZipArchive archive             = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create);
                CompressFolder(containingDirectory, string.Empty, archive);
                archive.Dispose();
                Binaries = memoryStream.ToArray();
            }
            RootHandlers = new Dictionary <string, SimpleWebHandler>();
            RootHandlers.Add("/", new DirectHandler()
            {
            });
            Printer.PrintMessage("Running web interface on port #b#{0}##.", Config.WebService.HttpPort);
            while (true)
            {
                var ctx = listener.GetContext();
                Task.Run(() =>
                {
                    HandleRequest(ctx);
                });
            }
            listener.Stop();
        }
        public void AddFileToArchiveCreatesEntryUnderDirectory(string fileName, string content)
        {
            // Arrange
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true);
            var fileInfo = CreateFile(fileName, content);

            // Act
            zip.AddFile(fileInfo, "");

            // Assert
            zip.Dispose();
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(1, zip.Entries.Count);
            AssertZipEntry(zip, fileName, content);
        }
Beispiel #10
0
 // decompress
 // @return value: true(decomp), false(no need), null(error)
 public static bool? Decompress(string ArcPath)
 {
     // check
     switch(Path.GetExtension(ArcPath)){
         case ".bms":
         case ".bme":
         case ".bml":
             // Nothing
             Console.WriteLine("Archive Extract: No need.");
             // Move File
             File.Move(ArcPath, ExtractPath + Path.GetFileName(ArcPath));
             return false;
         case ".zip":
             // Zip archive
             var ZipArc = new ZipArchive(new FileStream(ArcPath, FileMode.Open));
             ZipArc.ExtractToDirectory(ExtractPath);
             Console.WriteLine("Archive Extract: Success(Type: Zip).");
             ZipArc.Dispose();
             return true;
         case ".rar":
             // Rar archive
             // Load Unrar.dll
             var rarMgr = new UnRarDllMgr();
             var UnrarPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\bin\\unrar64.dll";
             if(!rarMgr.LoadModule(UnrarPath)) {
                 // Error Message
                 Console.WriteLine("Error: Can't Load \"Unrar64.dll\"");
                 return null;
             }
             // Filelist get
             var FileLists = rarMgr.GetFileList(ArcPath);
             // All Extract
             foreach(var FileData in FileLists) {
                 rarMgr.FileExtractToFolder(ArcPath, FileData.FileNameW, ExtractPath);
             }
             Console.WriteLine("Archive Extract: Success(Type: Rar).");
             // Release Unrar.dll
             rarMgr.UnloadModule();
             rarMgr.CloseArchive();
             return true;
         default:
             // Error Message
             Console.WriteLine("Error: this extension({0}) is not supported.",
                 Path.GetExtension(ArcPath));
             return null;
     }
 }
		public override void Deploy(Deployment deployment) {
			Logger.Debug(this, "Deploying to " + deployment.BinFolder + "...");
			ZipArchive archive = new ZipArchive(this.Read());
			try {
				foreach(ZipArchiveEntry entry in archive.Entries) {
					if(entry.Length == 0) continue;
					if(deployment.PackageContent.Manifest != null && entry.FullName == deployment.PackageContent.Manifest.ConfigurationFile) {
						string settingsPath = Path.Combine(deployment.SettingsFolder, entry.Name);
						this.ExtractEntry(entry, settingsPath);
						deployment.SettingsPath = settingsPath;
					} else {
						this.ExtractEntry(entry, Path.Combine(deployment.BinFolder, entry.FullName), true);
					}
				}
			} finally {
				archive.Dispose();
			}
			Logger.Debug(this, "Deployed");
		}
Beispiel #12
0
        protected override async Task<Stream> GetCompressedLogsInternal()
        {
            var logFileName = "Logs-Dump.zip";
            
            // create log file and output stream
            var zippedStorageFile = await logFolder.CreateFileAsync(logFileName, CreationCollisionOption.ReplaceExisting);
            var logoutputStream = await zippedStorageFile.OpenStreamForWriteAsync();
           
            // archive 
            var zipArchive = new ZipArchive(logoutputStream, ZipArchiveMode.Create, false);
            await ZipFolderContents(logFolder, zipArchive, logFileName);
            
            // release outfile stream
            await logoutputStream.FlushAsync();
            zipArchive.Dispose();
            logoutputStream.Dispose();

            // get inputstream for reading
            var loginputStream = await logFolder.OpenStreamForReadAsync(logFileName);
            return loginputStream;

        }
Beispiel #13
0
        public static bool Install(List<Parameter> parms, bool InstallObjectPayload)
        {
            FileStream fs = new FileStream(GetParameter("Name", parms) + ".NAVY", FileMode.Open);
            ZipArchive za = new ZipArchive(fs, ZipArchiveMode.Update);
            FileStream fs2 = new FileStream(GetParameter("Name", parms) + ".NAVY.Backup", FileMode.Create);
            ZipArchive zbackup = new ZipArchive(fs2, ZipArchiveMode.Update);
            ZipArchiveEntry manifest = za.GetEntry("manifest.xml");
            Package p = PackageFile.Load(manifest.Open());
            using (PowerShell psi = PowerShell.Create())
            {
                psi.AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned");
                psi.AddScript(NAVTools);

                File.Delete("object.txt");
                try { Directory.Delete("ORIGINAL", true); } catch { };
                try { Directory.Delete("DELTA", true); } catch { };
                try { Directory.Delete("RESULT", true); } catch { };
                Directory.CreateDirectory("ORIGINAL");
                Directory.CreateDirectory("DELTA");
                Directory.CreateDirectory("RESULT");
                Console.WriteLine("Exporting original objects from database...");
                foreach (var delta in p.Payload.Deltas)
                {
                    string FileName = delta.DeltaFile.Split('.')[0];

                    // Extract the delta from the ZIP
                    ZipArchiveEntry deltazip = za.GetEntry(delta.DeltaFile);
                    deltazip.ExtractToFile("DELTA\\" + delta.DeltaFile);

                    Console.WriteLine(" - object {0} {1}", delta.Type, delta.ID);
                    psi.AddScript("Export-NAVApplicationObject ORIGINAL\\" + FileName + ".TXT -DatabaseName " +
                                    GetParameter("DatabaseName", parms) +
                                    " -Force -Filter 'Type=" + delta.Type + ";Id=" + delta.ID + "'");
                    ExecutePowerShell(psi, false);
                    zbackup.CreateEntryFromFile("ORIGINAL\\" + FileName + ".TXT", FileName + ".TXT");
                }
                zbackup.Dispose();
                fs2.Close();

                Console.WriteLine("Applying deltas to objects...");
                psi.AddScript(@"Update-NAVApplicationObject -VersionListProperty FromModified -TargetPath ORIGINAL\*.txt -DeltaPath DELTA\*.delta –ResultPath RESULT\");
                ExecutePowerShell(psi, false);
            }

            if (InstallObjectPayload)
            {
                // Importing - First objects FOBs
                p.Payload.Objects.Sort(delegate (NAVObject a, NAVObject b)
                {
                    return a.ImportOrder.CompareTo(b.ImportOrder);
                });
                foreach (var fob in p.Payload.Objects)
                {
                    ZipArchiveEntry fobzip = za.GetEntry(fob.FileName);
                    fobzip.ExtractToFile(fob.FileName, true);

                    using (PowerShell psi2 = PowerShell.Create())
                    {
                        psi2.AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned");
                        psi2.AddScript(NAVTools);

                        Console.WriteLine("Importing FOB objects to database ...");

                        Console.WriteLine(" - fob file {0}", fob.FileName);
                        psi2.AddScript(@"Import-NAVApplicationObject -Confirm:$false " +
                                        fob.FileName +
                                        " -ImportAction Overwrite -DatabaseName " +
                                        GetParameter("DatabaseName", parms));
                        ExecutePowerShell(psi2, true);
                    }
                }
            }
            using (PowerShell psi2 = PowerShell.Create())
            {
                psi2.AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned");
                psi2.AddScript(NAVTools);

                Console.WriteLine("Importing new objects to database ...");
                foreach (var delta in p.Payload.Deltas)
                {
                    string FileName = delta.DeltaFile.Split('.')[0];
                    Console.WriteLine(" - object {0} {1}", delta.Type, delta.ID);
                    psi2.AddScript(@"Import-NAVApplicationObject -Confirm:$false RESULT\\" +
                                    FileName +
                                    ".TXT -DatabaseName " +
                                    GetParameter("DatabaseName", parms));
                    ExecutePowerShell(psi2, true);
                }
            }

            // Compiling
            using (PowerShell psi2 = PowerShell.Create())
            {
                psi2.AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned");
                psi2.AddScript(NAVTools);
                Console.WriteLine("Compiling objects ...");
                psi2.AddScript("Compile-NAVApplicationObject " +
                                GetParameter("DatabaseName", parms) + " -SynchronizeSchemaChanges Force");
                ExecutePowerShell(psi2, true);
            }
            za.Dispose();
            fs.Close();
            return true;
        }
        static void ReadZip(Stream stream)
        {
            var zipArchive = new ZipArchive(stream, ZipArchiveMode.Read);

            if (zipArchive.Entries.Count != 1) throw new Exception();
            var entryStream = zipArchive.Entries[0].Open();
            ReadXml(entryStream);
            entryStream.Close();
            entryStream.Dispose();

            zipArchive.Dispose();
        }
Beispiel #15
0
        public void DownLoadSyncData()
        {
            IList <Google.Apis.Drive.v3.Data.File> listfile = new List <Google.Apis.Drive.v3.Data.File>();
            var listRequest = driveService.Files.List();

            listRequest.Spaces = "appDataFolder";
            listRequest.Fields = "nextPageToken, files(id, name)";
            try
            {
                listfile = listRequest.Execute().Files.ToList();
            }
            catch
            {
                MessageBox.Show("Error downloading data from google drive. Please check your internet connection and try again.");
            }
            if (listfile.Count == 0)
            {
                return;
            }
            else
            {
                if (File.Exists(zipPath))
                {
                    File.Delete(zipPath);
                }
                var fileId          = listfile[0].Id;
                var downloadRequest = driveService.Files.Get(fileId);
                using (FileStream fs = new FileStream(listfile[0].Name, FileMode.Create))
                {
                    downloadRequest.MediaDownloader.ProgressChanged += Download_ProgressChanged;
                    try
                    {
                        downloadRequest.Download(fs);
                    }
                    catch
                    {
                        MessageBox.Show("Error downloading data from google drive. Please check your internet connection and try again.");
                    }
                }
                //After
                if (!Directory.Exists(startPath))
                {
                    Directory.CreateDirectory(startPath);
                }
                //ZipFile.ExtractToDirectory(zipPath, startPath);
                using (System.IO.Compression.ZipArchive zipLoader = ZipFile.Open(zipPath, ZipArchiveMode.Read))
                {
                    foreach (var entry in zipLoader.Entries)
                    {
                        string path = Path.Combine(startPath, entry.FullName);
                        if (!Directory.Exists(Path.GetDirectoryName(path)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(path));
                        }
                        try
                        {
                            entry.ExtractToFile(path, true);
                        }
                        catch
                        {
                        }
                    }
                    zipLoader.Dispose();
                }
                File.Delete(zipPath);
                App.Global.Book_Short_ViewModel.LoadListBookShort();
                (App.Current.MainWindow as WindowScreen).LoadTreeViewList();
                (App.Current.MainWindow as WindowScreen).LoadShelf();
            }
            Notification = "Download and Sync Successful!";
        }
Beispiel #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filename">
        /// Format:
        ///     ~\Filename.txt
        ///     ~\Directory1\Directory2\Filename.txt
        ///     ~/Filename.txt
        ///     ~/Directory1/Directory2/Filename.txt
        /// </param>
        /// <returns></returns>
        public Stream GetFileStream(string filename)
        {
            var parstedFilename = ParseFilename(filename);

            if (!_entryNames.Contains(parstedFilename))
            {
                string note = "";

                var entryWithAnotherCasing = _entryNames
                    .FirstOrDefault(en => en.Equals(parstedFilename, StringComparison.InvariantCultureIgnoreCase));

                if (entryWithAnotherCasing != null)
                {
                    note =  $" There's another entry with different casing '{entryWithAnotherCasing}'.";
                }

                throw new ArgumentException($"The file '{filename}' does not exist in the zip." + note);
            }

            var zipArchive = new ZipArchive(C1File.Open(ZipFilename, FileMode.Open, FileAccess.Read));

            var entryPath = filename.Substring(2).Replace('\\', '/');

            var entry = zipArchive.GetEntry(entryPath);
            if (entry == null)
            {
                zipArchive.Dispose();

                throw new InvalidOperationException($"Entry '{entryPath}' not found");
            }
            
            return new StreamWrapper(entry.Open(), () => zipArchive.Dispose());
        }
        private static string GenerateReport(EstadoDoProjeto resultadoGeral, string reportDirectory)
        {

            var reportPath = Path.Combine(reportDirectory, string.Format("{0}{1}.zip", "CodeMetricsReport", string.Format("-{0:yy-MM-dd-HH-mm}", DateTime.Now)));

            var reportTemplateFactory = new ReportTemplateFactory();
            var report = reportTemplateFactory.GetReport(resultadoGeral);
            var list = new[] { "*.css", "*.js" }.SelectMany(ext => Directory.GetFiles(Path.Combine(ApplicationPath, "ReportTemplate"), ext)).ToList();


            Directory.CreateDirectory(reportDirectory);
            using (var zipArchive = new ZipArchive(File.OpenWrite(reportPath), ZipArchiveMode.Create))
            {
                foreach (var item in list)
                {
                    var fileName = Path.GetFileName(item);
                    zipArchive.CreateEntryFromFile(item, fileName);
                    File.Copy(item, Path.Combine(reportDirectory, fileName), true);
                }
                var archiveEntry = zipArchive.CreateEntry("Index.html");
                using (var stream = archiveEntry.Open())
                using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
                    streamWriter.Write(report);
                reportPath = Path.Combine(reportDirectory, "Index.html");
                File.WriteAllText(reportPath, report, Encoding.UTF8);
                zipArchive.Dispose();
            }
            return reportPath;
        }
Beispiel #18
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();
        }
Beispiel #19
0
        /// <summary>
        /// Executes file operations.
        /// </summary>
        /// <param name="commands">The list of operations to be executed.</param>
        /// <param name="zip">Reference to the opened zip archive.</param>
        /// <returns>The number of changes executed.</returns>
        private static int Dispatch(List<Operation> commands, ZipArchive zip)
        {
            int changes = 0;

            try
            {
                Console.WriteLine(" OK!");
                foreach (Operation op in commands)
                {
                    switch (op.Type)
                    {
                        case "a":
                            {
                                string basePath = Path.GetDirectoryName(op.Filter);

                                if (null == basePath || string.Empty == basePath)
                                {
                                    basePath = Directory.GetCurrentDirectory();
                                }

                                try
                                {
                                    foreach (string file in Directory.GetFiles(basePath, Path.GetFileName(op.Filter)))
                                    {
                                        Console.Write("  Adding file " + file + " ...");

                                        try
                                        {
                                            string fileName = Path.GetFileName(file);

                                            if (zip.Mode == ZipArchiveMode.Update)
                                            {
                                                var existingEntry = zip.Entries.SingleOrDefault(e => e.Name.ToLowerInvariant() == fileName.ToLowerInvariant());
                                                if (null != existingEntry) existingEntry.Delete();
                                            }

                                            zip.CreateEntryFromFile(file, fileName, CompressionLevel.Optimal);
                                            changes++;
                                            Console.WriteLine(" OK!");
                                        }
                                        catch (FileNotFoundException)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Error: unable to locate file " + file);
                                        }
                                        catch (UnauthorizedAccessException)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Error: access denied to file " + file);
                                        }
                                        catch (IOException)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Error: caught exception while trying to read file " + file);
                                        }

                                        Thread.Sleep(1);
                                    }
                                }
                                catch (DirectoryNotFoundException)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("Error: unable to locate path " + basePath);
                                    return changes;
                                }
                                catch (UnauthorizedAccessException)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("Error: access denied to path " + basePath);
                                    return changes;
                                }

                                break;
                            }

                        case "r":
                            {
                                bool hasStart = !op.Filter.StartsWith("*");
                                string[] components = op.Filter.Split('*');
                                string filterStart = (components[0] != string.Empty) ? components[0] : null;
                                string filterEnd = (components[1] != string.Empty) ? components[1] : null;

                                List<ZipArchiveEntry> toRemove = new List<ZipArchiveEntry>();

                                foreach (var entry in zip.Entries)
                                {
                                    if (filterStart == null || (filterStart != null && entry.FullName.StartsWith(filterStart, StringComparison.InvariantCultureIgnoreCase)))
                                    {
                                        if (filterEnd == null || (filterEnd != null && entry.FullName.EndsWith(filterEnd, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            toRemove.Add(entry);
                                            Console.WriteLine("  Removing file " + entry.FullName + " ...");
                                        }
                                    }
                                }

                                if (toRemove.Count > 0)
                                {
                                    try
                                    {
                                        foreach (var entry in toRemove)
                                        {
                                            entry.Delete();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                    }

                                    changes++;
                                }

                                break;
                            }
                    }
                }
            }
            finally
            {
                if (null != zip) 
                {
                    zip.Dispose();
                }
            }

            return changes;
        }
Beispiel #20
0
        private static async Task AddFileToZipHelper(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();

            // Create zip archive to access compressed files in memory stream
            using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Update))
            {
                ZipArchiveEntry currentEntry = null;
                var fileName = "OEBPS/" + file.Name;
                
                // Unzip compressed file iteratively.
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    Debug.WriteLine(entry.FullName);
                    Debug.WriteLine(fileName);
                    if (entry.FullName == fileName)
                    {
                        currentEntry = entry;
                    }
                }

                if (currentEntry == null)
                {
                    // make a new entry
                    currentEntry = zipArchive.CreateEntry(fileName);
                }

                var contentType = file.ContentType;

                // TODO: catch other file types!
                using (var entryStream = currentEntry.Open())
                using (BinaryWriter writer = new BinaryWriter(entryStream))
                {
                    IBuffer buffer = await FileIO.ReadBufferAsync(file);
                    DataReader reader = DataReader.FromBuffer(buffer);
                    byte[] fileContent = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(fileContent);
                    writer.Write(fileContent);
                    
                    writer.Dispose();
                    reader.Dispose();
                }
                
                zipArchive.Dispose();
            }
            zipMemoryStream.Dispose();
        }
Beispiel #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filename">
        /// Format:
        ///     ~\Filename.txt
        ///     ~\Directory1\Directory2\Filename.txt
        ///     ~/Filename.txt
        ///     ~/Directory1/Directory2/Filename.txt
        /// </param>
        /// <returns></returns>
        public Stream GetFileStream(string filename)
        {
            var parstedFilename = ParseFilename(filename);

            if (!_entryNames.Contains(parstedFilename))
            {
                throw new ArgumentException($"The file {filename} does not exist in the zip");
            }

            var zipArchive = new ZipArchive(C1File.Open(ZipFilename, FileMode.Open, FileAccess.Read));

            var entryPath = filename.Substring(2).Replace('\\', '/');

            var entry = zipArchive.GetEntry(entryPath);
            if (entry == null)
            {
                zipArchive.Dispose();

                throw new InvalidOperationException($"Entry '{entryPath}' not found");
            }
            
            return new StreamWrapper(entry.Open(), () => zipArchive.Dispose());
        }
Beispiel #22
0
 public void Dispose()
 {
     _archive.Dispose();
     _ms.Dispose();
 }
Beispiel #23
0
        public bool Extract(string mmuZipFile, string outputDir)
        {
            System.IO.Compression.ZipArchive zip = ZipFile.Open(mmuZipFile, ZipArchiveMode.Update);
            string dir      = "";
            bool   noFolder = false;

            for (int i = 0; i < zip.Entries.Count; i++)
            {
                var p = zip.Entries[i].FullName.IndexOf('\\');
                if (p == -1)
                {
                    p = zip.Entries[i].FullName.IndexOf('/');
                }
                if (p >= 0)
                {
                    if ((i > 0) && (dir != zip.Entries[i].FullName.Substring(0, p)))
                    {
                        noFolder = true;
                    }
                    dir = zip.Entries[i].FullName.Substring(0, p);
                }
                else
                {
                    noFolder = true;
                }
            }

            if (noFolder)
            { //there is no folder in the zip archive containing all the files, folder needs to be created, extract MMU name from file and make sure the name is unique in the folder structure
                dir = NameMUUDir(zip);
                if (Directory.Exists(outputDir + dir))
                {
                    int k = 1;
                    while (Directory.Exists(outputDir + dir + "-" + k.ToString()))
                    {
                        k++;
                    }
                    dir = dir + "-" + k.ToString() + "\\";
                }
                dir = dir.Replace("mmu", "").Replace("MMU", "");
                zip.ExtractToDirectory(outputDir + dir);
            }
            else
            { //there is common folder - check if it is unque in the folder sturcture, if not change the folder name using MMU name and version
                if (Directory.Exists(outputDir + dir))
                {
                    Stream descFile = null;
                    for (int i = 0; i < zip.Entries.Count; i++)
                    {
                        if (zip.Entries[i].Name == "description.json")
                        {
                            descFile = zip.Entries[i].Open();
                            break;
                        }
                    }
                    if (descFile == null)
                    {
                        return(false);
                    }

                    byte[] descBuff = new byte[descFile.Length];
                    descFile.Read(descBuff, 0, Convert.ToInt32(descFile.Length));
                    var mmudescription = Serialization.FromJsonString <MMUDescription>(Encoding.UTF8.GetString(descBuff));
                    dir = mmudescription.Name + "-" + mmudescription.Version;
                    dir = dir.Replace("mmu", "").Replace("MMU", "");
                    if (Directory.Exists(outputDir + dir))
                    {
                        int k = 1;
                        while (Directory.Exists(outputDir + dir + "-" + k.ToString()))
                        {
                            k++;
                        }
                        dir = dir + "-" + k.ToString() + "\\";
                    }
                    else
                    {
                        dir += "\\";
                    }
                    descFile.Dispose();

                    Directory.CreateDirectory(outputDir + dir);

                    //extraction file by file
                    for (int i = 0; i < zip.Entries.Count; i++)
                    {
                        var p = zip.Entries[i].FullName.IndexOf('\\');
                        if (p == -1)
                        {
                            p = zip.Entries[i].FullName.IndexOf('/');
                        }
                        var basefile = zip.Entries[i].FullName.Substring(p + 1);
                        p = basefile.LastIndexOf('\\');
                        if (p == -1)
                        {
                            p = basefile.LastIndexOf('/');
                        }
                        if (p > -1)
                        {
                            if (!Directory.Exists(outputDir + dir + basefile.Substring(0, p)))
                            {
                                Directory.CreateDirectory(outputDir + dir + basefile.Substring(0, p));
                            }
                        }
                        if (basefile != "") //it is empty in case of root directory entry
                        {
                            zip.Entries[i].ExtractToFile(outputDir + dir + basefile);
                        }
                    }
                }
                else
                {
                    // dir = dir.Replace("mmu", "").Replace("MMU", "");
                    zip.ExtractToDirectory(outputDir);
                }
            }


            zip.Dispose();
            return(true);
            //ZipFile.ExtractToDirectory(mmuZipFile, outputDir);
        }
        //-------------------------------------------------------------------------------
        #region +[static]copyToLocal 選択フォルダからローカルへコピー
        //-------------------------------------------------------------------------------
        //
        public async static void copyToLocal(StorageFolder rootDir, Action<int, int, int, int> progressReportFunc = null) {
            var localDir = Windows.Storage.ApplicationData.Current.LocalFolder;
            var dataDir_dst = await localDir.CreateFolderAsync(DATA_FOLDER_NAME, CreationCollisionOption.OpenIfExists);
            var dataDir_src = await rootDir.GetFolderAsync("CDATA");

            var fileList = await dataDir_src.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery);

            if (progressReportFunc != null) { progressReportFunc(0, 2, 0, fileList.Count); }

            int count = 0;
            foreach (var file in fileList) {
                await file.CopyAsync(dataDir_dst, file.Name, NameCollisionOption.ReplaceExisting);
                count++;
                if (progressReportFunc != null) { progressReportFunc(0, 2, count, fileList.Count); }
            }

            var imageDir = await localDir.CreateFolderAsync(IMAGES_FOLDER_NAME, CreationCollisionOption.OpenIfExists);

            var imgFile = await rootDir.GetFileAsync("C084CUTL.CCZ");
            MemoryStream ms = new MemoryStream();
            using (Stream stream = (await imgFile.OpenReadAsync()).AsStream()) {
                byte[] buf = new byte[0x10000000];
                while (true) {
                    int r = stream.Read(buf, 0, buf.Length);
                    if (r <= 0) { break; }
                    ms.Write(buf, 0, r);
                }
            }
            var zipArchive = new ZipArchive(ms);

            if (progressReportFunc != null) { progressReportFunc(1, 2, 0, zipArchive.Entries.Count); }
            count = 0;

            foreach (var entry in zipArchive.Entries) {
                string name = entry.Name;
                using (Stream dstStr = await imageDir.OpenStreamForWriteAsync(name, CreationCollisionOption.ReplaceExisting))
                using (Stream srcStr = entry.Open()) {
                    int size;
                    const int BUF_SIZE = 0x100000;
                    byte[] buf = new byte[BUF_SIZE];
                    size = srcStr.Read(buf, 0, BUF_SIZE);
                    while (size > 0) {
                        dstStr.Write(buf, 0, size);
                        size = srcStr.Read(buf, 0, BUF_SIZE);
                    }
                    count++;
                    if (progressReportFunc != null) { progressReportFunc(1, 2, count, zipArchive.Entries.Count); }
                }
            }
            if (progressReportFunc != null) { progressReportFunc(2, 2, count, zipArchive.Entries.Count); }

            ms.Dispose();
            zipArchive.Dispose();
        }
Beispiel #25
0
 public void Dispose()
 {
     _zipArchive.Dispose();
 }
Beispiel #26
0
        /// <summary>
        /// Open a ZIP file archive.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The file name of the ZIP archive to open.</param>
        /// <param name="flags">The mode to use to open the archive.</param>
        /// <returns>TRUE on success or the error code.</returns>
        public PhpValue open(Context ctx, string filename, int flags = 0)
        {
            if ((flags & CHECKCONS) != 0)
            {
                PhpException.ArgumentValueNotSupported(nameof(flags), nameof(CHECKCONS));
            }

            if (_archive != null)
            {
                // Save the changes to the current archive before opening another one
                _archive.Dispose();
                _archive = null;
            }

            try
            {
                string fullPath = FileSystemUtils.AbsolutePath(ctx, filename);

                FileMode mode;
                if (File.Exists(fullPath))
                {
                    if ((flags & EXCL) != 0)
                    {
                        PhpException.Throw(PhpError.Warning, Resources.Resources.file_exists, fullPath);
                        return(ER_EXISTS);
                    }
                    else if ((flags & OVERWRITE) != 0)
                    {
                        mode = FileMode.Truncate;
                    }
                    else
                    {
                        mode = FileMode.Open;
                    }
                }
                else
                {
                    if ((flags & CREATE) != 0)
                    {
                        mode = FileMode.Create;
                    }
                    else
                    {
                        PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, fullPath);
                        return(ER_NOENT);
                    }
                }

                var fileStream = File.Open(fullPath, mode);
                _archive      = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update);
                this.filename = fullPath;

                return(true);
            }
            catch (IOException e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_OPEN);
            }
            catch (InvalidDataException e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_INCONS);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(ER_INTERNAL);
            }
        }
        public void AddFileInUseTests()
        {
            // Arrange
            var fileName = @"x:\test\temp.txt";
            var exception = new IOException("file in use");
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);
            var tracer = new Mock<ITracer>();
            var file = new Mock<FileInfoBase>();

            // setup
            file.Setup(f => f.OpenRead())
                .Throws(exception);
            file.SetupGet(f => f.FullName)
                .Returns(fileName);
            tracer.Setup(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                  .Callback((string message, IDictionary<string, string> attributes) =>
                  {
                      Assert.Contains("error", attributes["type"]);
                      Assert.Contains(fileName, attributes["text"]);
                      Assert.Contains("file in use", attributes["text"]);
                  });

            // Act
            zip.AddFile(file.Object, tracer.Object, String.Empty);
            zip.Dispose();

            // Assert
            tracer.Verify(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()), Times.Once());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(0, zip.Entries.Count);
        }
 private static void WeaponizePackage(string PackageFullPath)
 {
     var archive = new ZipArchive(new FileStream(PackageFullPath, FileMode.Open), ZipArchiveMode.Update);
     var entry = archive.GetEntry("_rels/.rels");
     Stream f = entry.Open();
     f.Position = 0;
     byte[] bytes = new byte[1100];
     for (int i = 0; i < 260144; i++)
     {
         f.Write(bytes, 0, bytes.Length);
     }
     f.Close();
     archive.Dispose();
 }
Beispiel #29
0
 public static bool Build(List<Parameter> parms)
 {
     Console.WriteLine("Building NAVY Package for {0} Version {1}", GetParameter("Name", parms), GetParameter("Version", parms));
     FileStream fs = new FileStream(GetParameter("Name", parms) + ".NAVY", FileMode.Create);
     ZipArchive za = new ZipArchive(fs, ZipArchiveMode.Create);
     Package pack = new Package();
     pack.App = new App();
     pack.Payload = new Payload();
     pack.App.Id = Guid.NewGuid().ToString();
     pack.App.Name = GetParameter("Name", parms);
     pack.App.Version = GetParameter("Version", parms);
     pack.App.CompatibilityId = "";
     pack.App.Description = "";
     pack.App.Publisher = "";
     pack.Payload.Objects = new List<NAVObject>();
     pack.Payload.Deltas = new List<Delta>();
     int ImportOrder = 1;
     foreach (var p in parms)
     {
         if (p.Type == "FOB")
         {
             pack.Payload.Objects.Add(new NAVObject
             {
                 FileName = Path.GetFileName(p.Value),
                 Type = "FOB",
                 ImportOrder = ImportOrder.ToString()
             });
             Console.WriteLine("* Adding FOB: {0}", Path.GetFileName(p.Value));
             za.CreateEntryFromFile(p.Value, Path.GetFileName(p.Value));
             ImportOrder++;
         }
         if (p.Type == "TXT")
         {
             pack.Payload.Objects.Add(new NAVObject
             {
                 FileName = Path.GetFileName(p.Value),
                 Type = "TXT",
                 ImportOrder = ImportOrder.ToString()
             });
             Console.WriteLine("* Adding TXT: {0}", Path.GetFileName(p.Value));
             za.CreateEntryFromFile(p.Value, Path.GetFileName(p.Value));
             ImportOrder++;
         }
         if (p.Type == "DELTAFILES")
         {
             foreach (var f in Directory.EnumerateFiles(p.Value, "*.DELTA"))
             {
                 string Type = "";
                 string DeltaFile = Path.GetFileName(f);
                 switch (DeltaFile.Substring(0, 3))
                 {
                     case "TAB":
                         Type = "Table";
                         break;
                     case "COD":
                         Type = "Codeunit";
                         break;
                     case "PAG":
                         Type = "Page";
                         break;
                     case "REP":
                         Type = "Report";
                         break;
                     case "XML":
                         Type = "XMLport";
                         break;
                     case "QUE":
                         Type = "Query";
                         break;
                     case "MEN":
                         Type = "Menusuite";
                         break;
                 }
                 var id = DeltaFile.Substring(3, DeltaFile.IndexOf('.') - 3);
                 pack.Payload.Deltas.Add(new Delta
                 {
                     DeltaFile = DeltaFile,
                     Type = Type,
                     ID = id
                 });
                 Console.WriteLine("* Adding delta: {0}", DeltaFile);
                 za.CreateEntryFromFile(f, DeltaFile);
             }
         }
     }
     var manifest = za.CreateEntry("manifest.xml");
     using (StreamWriter writer = new StreamWriter(manifest.Open()))
     {
         Console.WriteLine("* Adding manifest.xml");
         writer.Write(PackageFile.Save(pack));
     }
     za.Dispose();
     fs.Close();
     return true;
 }
Beispiel #30
0
 public static XRefArchive Open(string file, XRefArchiveMode mode)
 {
     if (file == null)
     {
         throw new ArgumentNullException(nameof(file));
     }
     FileStream fs = null;
     ZipArchive archive = null;
     try
     {
         bool isReadOnly = false;
         List<string> entries;
         switch (mode)
         {
             case XRefArchiveMode.Read:
                 isReadOnly = true;
                 goto case XRefArchiveMode.Update;
             case XRefArchiveMode.Update:
                 if (!File.Exists(file))
                 {
                     throw new FileNotFoundException($"File not found: {file}", file);
                 }
                 fs = File.Open(file, FileMode.Open, isReadOnly ? FileAccess.Read : FileAccess.ReadWrite);
                 archive = new ZipArchive(fs, isReadOnly ? ZipArchiveMode.Read : ZipArchiveMode.Update);
                 entries = (from entry in archive.Entries
                            select entry.FullName).ToList();
                 entries.Sort(StringComparer.OrdinalIgnoreCase);
                 break;
             case XRefArchiveMode.Create:
                 var directory = Path.GetDirectoryName(file);
                 if (!string.IsNullOrEmpty(directory))
                 {
                     Directory.CreateDirectory(directory);
                 }
                 fs = File.Create(file);
                 archive = new ZipArchive(fs, ZipArchiveMode.Update);
                 entries = new List<string>();
                 break;
             default:
                 throw new ArgumentOutOfRangeException(nameof(mode));
         }
         return new XRefArchive(mode, archive, entries);
     }
     catch (Exception) when (fs != null)
     {
         if (archive != null)
         {
             archive.Dispose();
         }
         fs.Close();
         throw;
     }
 }