/// <summary> /// This is the "real" main. The class main() instantiates a tar object /// for the application and then calls this method. Process the arguments /// and perform the requested operation. /// </summary> public void InstanceMain(string[] argv) { TarArchive archive = null; int argIdx = this.ProcessArguments(argv); if (this.archiveName != null && !this.archiveName.Equals("-")) { if (operation == Operation.Create) { string dirName = Path.GetDirectoryName(archiveName); if ((dirName.Length > 0) && !Directory.Exists(dirName)) { Console.Error.WriteLine("Directory for archive doesnt exist"); return; } } else { if (File.Exists(this.archiveName) == false) { Console.Error.WriteLine("File does not exist " + this.archiveName); return; } } } if (operation == Operation.Create) { // WRITING Stream outStream = Console.OpenStandardOutput(); if (this.archiveName != null && !this.archiveName.Equals("-")) { outStream = File.Create(archiveName); } if (outStream != null) { switch (this.compression) { case Compression.Compress: outStream = new DeflaterOutputStream(outStream); break; case Compression.Gzip: outStream = new GZipOutputStream(outStream); break; case Compression.Bzip2: outStream = new BZip2OutputStream(outStream, 9); break; } archive = TarArchive.CreateOutputTarArchive(outStream, this.blockingFactor); } } else { // EXTRACTING OR LISTING Stream inStream = Console.OpenStandardInput(); if (this.archiveName != null && !this.archiveName.Equals("-")) { inStream = File.OpenRead(archiveName); } if (inStream != null) { switch (this.compression) { case Compression.Compress: inStream = new InflaterInputStream(inStream); break; case Compression.Gzip: inStream = new GZipInputStream(inStream); break; case Compression.Bzip2: inStream = new BZip2InputStream(inStream); break; } archive = TarArchive.CreateInputTarArchive(inStream, this.blockingFactor); } } if (archive != null) { // SET ARCHIVE OPTIONS archive.SetKeepOldFiles(this.keepOldFiles); archive.AsciiTranslate = this.asciiTranslate; archive.SetUserInfo(this.userId, this.userName, this.groupId, this.groupName); } if (archive == null) { Console.Error.WriteLine("no processing due to errors"); } else if (operation == Operation.Create) { // WRITING if (verbose) { archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage); } for (; argIdx < argv.Length; ++argIdx) { string[] fileNames = GetFilesForSpec(argv[argIdx]); if (fileNames.Length > 0) { foreach (string name in fileNames) { TarEntry entry = TarEntry.CreateEntryFromFile(name); archive.WriteEntry(entry, true); } } else { Console.Error.Write("No files for " + argv[argIdx]); } } } else if (operation == Operation.List) { // LISTING archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage); archive.ListContents(); } else { // EXTRACTING string userDir = Environment.CurrentDirectory; if (verbose) { archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage); } if (userDir != null) { archive.ExtractContents(userDir); } } if (archive != null) { // CLOSE ARCHIVE archive.Close(); } }
/// <summary> /// Zips the specified directory files to a zip file. /// </summary> /// <param name="zipFilename">The filename and path of the zip file to create.</param> /// <param name="zipDirectorPath">The directory of the files to zip.</param> /// <param name="pattern">The directory search pattern.</param> /// <param name="searchOption">The directory search option.</param> /// <param name="extensionRegularExpression">The regular expression for excluding files from being compressed.</param> /// <param name="filesToInclude">The list of files that are only to be compressed.</param> /// <remarks>Extension Regular Expression should be in the form 'jpg|JPG|gif|GIF|doc|DOC|pdf|PDF'</remarks> public static void Compress(string zipFilename, string zipDirectorPath, string pattern, SearchOption searchOption, string extensionRegularExpression, List <string> filesToInclude) { // Get the collection of files in the directory string[] files = Directory.GetFiles(zipDirectorPath.TrimEnd('\\') + "\\", pattern, searchOption); // Create all the streams using (Stream zipStream = File.Create(zipFilename)) using (BZip2OutputStream stream = new BZip2OutputStream(zipStream, 9)) using (TarArchive archive = TarArchive.CreateOutputTarArchive(stream, TarBuffer.DefaultBlockFactor)) { // Assign the archive properties archive.SetKeepOldFiles(false); archive.AsciiTranslate = true; archive.SetUserInfo(0, "anonymous", 0, "None"); // For each file found foreach (string file in files) { bool excludeFile = false; // If a regular expression has been supplied. if (!String.IsNullOrEmpty(extensionRegularExpression)) { excludeFile = Regex.IsMatch(file.Trim(), @".*\.(" + extensionRegularExpression + @")$"); } // Find all files that need to be included. if (filesToInclude != null && !excludeFile) { // Should the current file be included. IEnumerable <string> includeFiles = filesToInclude.Where(u => u.ToLower() == file.ToLower()); if (includeFiles.Count() > 0) { excludeFile = false; } else { excludeFile = true; } } // If file should not be excluded if (!excludeFile) { // Get the relative info string relativePath = Path.GetDirectoryName(file).TrimEnd('\\') + "\\"; relativePath = relativePath.Replace(zipDirectorPath.TrimEnd('\\') + "\\", "").Replace("\\", "/"); // Get the file entry and set the relative // path as the name of the entry. TarEntry entry = TarEntry.CreateEntryFromFile(file); entry.Name = (!String.IsNullOrEmpty(relativePath) ? relativePath.TrimEnd('/') + "/" : "") + Path.GetFileName(file); // Write to the zip file. archive.WriteEntry(entry, true); } } // CLose all the streams. archive.Close(); stream.Close(); zipStream.Close(); } }
private void OnWorkerDo(object sender, DoWorkEventArgs e) { try { var file = Destination; var sources = Sources; using (Stream output = File.Create(file)) { Worker.ReportProgress(5, string.Format("Creating {0}", file)); using (TarArchive archive = TarArchive.CreateOutputTarArchive(output, TarBuffer.DefaultBlockFactor)) { archive.ProgressMessageEvent += (a, b, c) => { if (!string.IsNullOrWhiteSpace(c)) { Console.Write("{0}; {1}", b.Name, c); } }; archive.SetKeepOldFiles(false); archive.SetUserInfo(1, Environment.UserName, 1, null); int factor = (int)75 / sources.Count; int progress = 10; foreach (string s in sources) { progress += factor; Worker.ReportProgress(progress, string.Format("Adding {0}", s)); TarEntry entry = TarEntry.CreateEntryFromFile(s); archive.WriteEntry(entry, true); } archive.Close(); Worker.ReportProgress(85, string.Format("Finished creating {0}", file)); if (Checksum.Checked) { Worker.ReportProgress(95, "Calculating MD5 checksum of created archive"); string checksum; using (var md5 = MD5.Create()) { using (var stream = new BufferedStream(File.OpenRead(file), 1024 * 1024)) { byte[] bytes = md5.ComputeHash(stream); checksum = string.Concat(bytes.Select(b => b.ToString("X2")).ToArray()); } } Worker.ReportProgress(98, string.Format("Checksum is {0}", checksum)); using (var stream = new FileStream(file, FileMode.Append)) { var bytes = Encoding.UTF8.GetBytes(string.Format("{0} {1}\n", checksum, Path.GetFileName(file))); stream.Write(bytes, 0, bytes.Length); } var renamed = file + ".md5"; if (File.Exists(renamed)) { File.Delete(renamed); } File.Move(file, (file = renamed)); Worker.ReportProgress(99, string.Format("Renamed archive to {0}", file)); } Worker.ReportProgress(100, "Package is ready to be flashed via ODIN"); } } } catch (Exception ex) { Worker.ReportProgress(99, "Error occurred while creating archive"); Worker.ReportProgress(100, ex.Message); } }