//public void Zip(IEnumerable<string> files) //{ // foreach (string file in files) // { // AddFile(file); // } //} // bool entryAsFilename = false //public void AddFile(string file, string entryName = null) public void AddFile(string file, string entryName) { //if (entryName == null) //{ // if (_entryAsFilename) // entryName = zPath.GetFileName(file); // else if (_rootDirectory != null && file.StartsWith(_rootDirectory)) // entryName = file.Substring(_rootDirectory.Length); // else // entryName = file; //} if (entryName == null) { throw new PBException("entryName is null"); } if (_setSlashInEntryName) { entryName = entryName.Replace('\\', '/'); } ZipArchiveEntry entry = _zipArchive.GetEntry(entryName); if (entry != null) { entry.Delete(); } _zipArchive.CreateEntryFromFile(file, entryName, _compressionLevel); }
private void ZipperAddFile(System.IO.Compression.ZipArchive zipper, dodSON.Core.FileStorage.ICompressedFileStoreItem item) { // create new zip item zipper.CreateEntryFromFile(item.OriginalFilename, item.RootFilename, (item.CompressionStrategy == CompressionStorageStrategy.Compress) ? CompressionLevel.Optimal : CompressionLevel.NoCompression); }
public static void Create ( string zippedFileName , IEnumerable<string> originalFiles , Func<string, string> onCreateEntryProcessFunc//= null ) { using ( var fileStream = new FileStream ( zippedFileName , FileMode.OpenOrCreate , FileAccess.Write , FileShare.None ) ) { using (ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Create)) { foreach (var file in originalFiles) { var entryName = onCreateEntryProcessFunc(file); archive.CreateEntryFromFile(file, entryName); } //archive.Dispose(); } } }
public override bool Execute() { if (SourceFiles == null && SourceDirectoryName == null) { Log.LogError( $"{nameof (ZipArchive)}: either {nameof (SourceFiles)} or " + $"{nameof (SourceDirectoryName)} must be provided."); return(false); } if (SourceFiles != null) { using (var stream = File.OpenWrite(DestinationArchiveFileName)) using (var archive = new SIOCZipArchive(stream, ZipArchiveMode.Create, true, Encoding.UTF8)) { foreach (var item in SourceFiles) { var fullPath = item.GetMetadata("FullPath") ?? item.ItemSpec; archive.CreateEntryFromFile(fullPath, item.ItemSpec); } } return(true); } if (!Directory.Exists(SourceDirectoryName)) { throw new DirectoryNotFoundException(SourceDirectoryName); } var fullSourceDirectoryName = SourceDirectoryName.TrimEnd( Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var sourceDirectoryName = fullSourceDirectoryName; if (RenameBaseDirectoryTo != null) { sourceDirectoryName = Path.Combine( Path.GetDirectoryName(fullSourceDirectoryName), Path.GetFileName(RenameBaseDirectoryTo)); Directory.Move(fullSourceDirectoryName, sourceDirectoryName); } Log.LogMessage( MessageImportance.High, "Creating archive: {0}", DestinationArchiveFileName); Directory.CreateDirectory(Path.GetDirectoryName(DestinationArchiveFileName)); ZipFile.CreateFromDirectory( sourceDirectoryName, DestinationArchiveFileName, CompressionLevel.Optimal, includeBaseDirectory: true); return(true); }
private static void ZipOutputs(HashSet <string> inputs, string output) { System.IO.Compression.ZipArchive outputs = ZipFile.Open(output, ZipArchiveMode.Create); foreach (var input in inputs) { outputs.CreateEntryFromFile(input, Path.GetFileName(input), CompressionLevel.Optimal); } }
private void CompressFile() { if (File.Exists($@"logs\battlelog\{date:yyyy-MM-dd}.log")) { using (var zipfile = new ZipArchive(File.Create($@"logs\battlelog\{date:yyyy-MM-dd}.zip"), ZipArchiveMode.Create)) zipfile.CreateEntryFromFile($@"logs\battlelog\{date:yyyy-MM-dd}.log", $"{date:yyyy-MM-dd}.log"); File.Delete($@"logs\battlelog\{date:yyyy-MM-dd}.log"); } }
private static void CreateZipArchive(string zipFileName, IEnumerable<string> fileNames) { using (var fileStream = File.Create(zipFileName)) using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create)) { foreach (var fileName in fileNames) zipArchive.CreateEntryFromFile(fileName, Path.GetFileName(fileName), CompressionLevel.Optimal); } }
public override bool Execute() { if (File.Exists(DestinationArchive) && OverwriteDestination == true) { Log.LogMessage(MessageImportance.Low, "{0} already existed, deleting before zipping...", SourceDirectory, DestinationArchive); File.Delete(DestinationArchive); } Log.LogMessage(MessageImportance.High, "Compressing {0} into {1}...", SourceDirectory, DestinationArchive); if (!Directory.Exists(Path.GetDirectoryName(DestinationArchive))) Directory.CreateDirectory(Path.GetDirectoryName(DestinationArchive)); if (ExcludePatterns == null) { ZipFile.CreateFromDirectory(SourceDirectory, DestinationArchive); } else { // convert to regular expressions Regex[] regexes = new Regex[ExcludePatterns.Length]; for (int i = 0; i < ExcludePatterns.Length; ++i) regexes[i] = new Regex(ExcludePatterns[i].ItemSpec, RegexOptions.IgnoreCase); using (FileStream writer = new FileStream(DestinationArchive, FileMode.CreateNew)) { using (ZipArchive zipFile = new ZipArchive(writer, ZipArchiveMode.Create)) { var files = Directory.GetFiles(SourceDirectory, "*", SearchOption.AllDirectories); foreach (var file in files) { // look for a match bool foundMatch = false; foreach (var regex in regexes) { if (regex.IsMatch(file)) { foundMatch = true; break; } } if (foundMatch) { Log.LogMessage(MessageImportance.Low, "Excluding {0} from archive.", file); continue; } var relativePath = MakeRelativePath(SourceDirectory, file); zipFile.CreateEntryFromFile(file, relativePath, CompressionLevel.Optimal); } } } } return true; }
public static void Test_OpenXml_Zip_01(string docxFile, string directory, bool useSlash, bool addDirectoryEntry) { // ok useSlash = false, addDirectoryEntry = false // bad useSlash = false, addDirectoryEntry = true le fichier est corrompu // ok useSlash = true, addDirectoryEntry = true // ok useSlash = true, addDirectoryEntry = false if (zFile.Exists(docxFile)) { zFile.Delete(docxFile); } int l = directory.Length; if (!directory.EndsWith("\\")) { l++; } //using (FileStream fs = new FileStream(docxFile, FileMode.OpenOrCreate)) using (FileStream fs = zFile.Open(docxFile, FileMode.OpenOrCreate)) using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update, false, Encoding.UTF8)) { int fileCount = 0; int directoryCount = 0; foreach (FileSystemInfo file in new DirectoryInfo(directory).EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories)) { string entryName = file.FullName.Substring(l); if (useSlash) { entryName = entryName.Replace('\\', '/'); } if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { if (useSlash) { entryName = entryName + "/"; } else { entryName = entryName + "\\"; } if (addDirectoryEntry) { Trace.WriteLine($"add directory \"{entryName}\""); ZipArchiveEntry entry = zipArchive.CreateEntry(entryName); directoryCount++; } } else { Trace.WriteLine($"add file \"{entryName}\""); zipArchive.CreateEntryFromFile(file.FullName, entryName); fileCount++; } } Trace.WriteLine($"total {fileCount + directoryCount} entries {fileCount} files {directoryCount} directories"); } }
public static void CreateArchive(string inputFileName, string outputFileName) { using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write)) { using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create)) { string entryName = Path.GetFileName(inputFileName); archive.CreateEntryFromFile(inputFileName, entryName, CompressionLevel.Optimal); } } }
public static void Test_ZipArchive_AddFile_01(string zipFile, string file, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal, FileMode fileMode = FileMode.OpenOrCreate) { using (FileStream fileStream = new FileStream(zipFile, fileMode)) { using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update)) { archive.CreateEntryFromFile(file, entryName, compressionLevel); } } }
private static void CreateZipArchive(string workingDirectory, string zipFileName, IEnumerable<string> fileNames) { using (var fileStream = File.Create(zipFileName)) using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create)) { foreach (var fileName in fileNames) { var relativePath = GetRelativePath(fileName, workingDirectory); zipArchive.CreateEntryFromFile(fileName, relativePath, CompressionLevel.Optimal); } } }
public string CompressFile(string path, string relativeTodir) { string zipFilePath = Path.GetTempFileName(); using (FileStream zipStream = new FileStream(zipFilePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) { string entryName = Path.GetFileName(path); if (!string.IsNullOrWhiteSpace(relativeTodir)) { entryName = path.MakeRelativePath(relativeTodir).Replace('\\', '/'); } archive.CreateEntryFromFile(path, entryName); } return zipFilePath; }
public void Create(ArgumentsReader argumentsReader) { var directoryName = Path.GetDirectoryName(argumentsReader.ImageFilePaths[1]); var zipFilePath = Path.Combine(directoryName, argumentsReader.DocumentFileNameWithoutExtension + ".sopimage"); // ファイルの上書き確認 if (File.Exists(zipFilePath)) { var message = string.Format("既に「{0}」ファイルが存在します。上書きしてよろしいですか?", Path.GetFileName(zipFilePath)); var result = MessageBox.Show(message, "ファイルの上書き確認", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { File.Delete(zipFilePath); } else { MessageBox.Show("sopimageファイルの作成を中断しました。"); // 画像ファイルは消す。 deleteImageFiles(argumentsReader); return; } } using (var fileStream = new FileStream(zipFilePath, FileMode.CreateNew)) { using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) { foreach (var imageFilePath in argumentsReader.ImageFilePaths) { var newImageFileName = imageFilePath.Key + Path.GetExtension(imageFilePath.Value); archive.CreateEntryFromFile(imageFilePath.Value, newImageFileName); } } } // zipファイルが作成できたら、ファイルを削除 deleteImageFiles(argumentsReader); // 完了ダイアログを表示。 { var message = string.Format("「{0}」を作成しました。ファイルがあるフォルダを開きますか?", Path.GetFileName(zipFilePath)); var result = MessageBox.Show(message, "sopimageファイルを作成しました。", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { System.Diagnostics.Process.Start( "EXPLORER.EXE", string.Format(@"/select,""{0}""", zipFilePath)); } } }
protected override Task<Stream> GetCompressedLogsInternal() { var ms = new MemoryStream(); using (var a = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var file in logFolder.GetFiles()) { a.CreateEntryFromFile(file.FullName, file.Name); } } ms.Position = 0; return Task.FromResult<Stream>(ms); }
static void Main(string[] args) { using (System.IO.Compression.ZipArchive zip = ZipFile.Open("results.zip", ZipArchiveMode.Create)) { for (int i = 0; i < 2; ++i) { var inputFilter = string.Format(CultureInfo.InvariantCulture, String.Format("{0}_*", i)); HashSet <string> inputFiles = CollectFiles(LocalStoragePath, inputFilter); zip.CreateEntry(String.Format("{0}/", i)); foreach (var file in inputFiles) { zip.CreateEntryFromFile(file, String.Format("{0}/{1}", i, Path.GetFileName(file))); } } } }
public static System.Byte[] CreateZipArchive(System.Collections.Generic.Dictionary <System.String, System.String> Files) { if ((Files == null) || (Files.Count == 0)) { return(null); } using (System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream()) { using (System.IO.Compression.ZipArchive ZipArchive = new System.IO.Compression.ZipArchive(MemoryStream, System.IO.Compression.ZipArchiveMode.Create, false)) foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> File in Files) { ZipArchive.CreateEntryFromFile(File.Value, File.Key); } return(MemoryStream.ToArray()); } }
public static void Test_OpenXml_Zip_01(string docxFile, string directory, bool useSlash, bool addDirectoryEntry) { // ok useSlash = false, addDirectoryEntry = false // bad useSlash = false, addDirectoryEntry = true le fichier est corrompu // ok useSlash = true, addDirectoryEntry = true // ok useSlash = true, addDirectoryEntry = false if (zFile.Exists(docxFile)) zFile.Delete(docxFile); int l = directory.Length; if (!directory.EndsWith("\\")) l++; using (FileStream fs = new FileStream(docxFile, FileMode.OpenOrCreate)) using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update, false, Encoding.UTF8)) { int fileCount = 0; int directoryCount = 0; foreach (FileSystemInfo file in new DirectoryInfo(directory).EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories)) { string entryName = file.FullName.Substring(l); if (useSlash) entryName = entryName.Replace('\\', '/'); if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { if (useSlash) entryName = entryName + "/"; else entryName = entryName + "\\"; if (addDirectoryEntry) { Trace.WriteLine($"add directory \"{entryName}\""); ZipArchiveEntry entry = zipArchive.CreateEntry(entryName); directoryCount++; } } else { Trace.WriteLine($"add file \"{entryName}\""); zipArchive.CreateEntryFromFile(file.FullName, entryName); fileCount++; } } Trace.WriteLine($"total {fileCount + directoryCount} entries {fileCount} files {directoryCount} directories"); } }
public static void BackupFiles(string filename) { var zipFile = new FileStream(filename, FileMode.Create); using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Create)) { foreach (var name in FileNames.Members) { try { archive.CreateEntryFromFile(Path.Combine(SavePath, name), name); } catch (Exception) { MessageBox.Show("No file " + name + " generated to backup yet. Continuing...", "File Not Backed Up"); } } } }
private JobResult ZipOutputs(HashSet <string> inputs, string output) { try { using (System.IO.Compression.ZipArchive outputs = ZipFile.Open(output, ZipArchiveMode.Create)) { foreach (var input in inputs) { outputs.CreateEntryFromFile(input, Path.GetFileName(input), CompressionLevel.Optimal); } } return(new JobResult { OutputFile = output }); } catch (Exception ex) { var error = string.Format("Failed to zip outputs: {0}", ex.ToString()); return(null); } }
/// <summary> /// Compresses the files to zip archive. /// </summary> /// <param name="zipArchivePath">The zip file path.</param> /// <param name="filesToZip">The files to zip.</param> /// <returns></returns> /// Erstellt von Joshua Frey, am 15.01.2016 public bool CompressFilesToZipArchive(string zipArchivePath, List<string> filesToZip) { using (FileStream zipToOpen = new FileStream(zipArchivePath, FileMode.OpenOrCreate)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)) { foreach (string exportFilePath in filesToZip) { if (File.Exists(exportFilePath)) { string fileName = Path.GetFileName(exportFilePath); archive.CreateEntryFromFile(exportFilePath, fileName, CompressionLevel.Optimal); } else { throw new NWATException(MessageZipProblemFileMissing(exportFilePath)); } } } } return true; }
private void Compress_Logs() { if (ServerSettings.RotateLogs_Zip) { //compress List<string> compress = new List<string>(); foreach (string file in GetFileNames()) { if (!file.Contains(".zip")) { compress.Add(file); } } //remove current logs file from compress list compress.Remove(new FileInfo(GetCurrentLogFile()).Name); foreach (string file_ext in compress) { string file = file_ext.Replace("txt",""); string path = Path.Combine(GetDirectory(), file); if (File.Exists(path + "txt")) { using (System.IO.FileStream fs = new System.IO.FileStream(@path + "zip", System.IO.FileMode.Create)) using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create)) { arch.CreateEntryFromFile(@path + "txt", file_ext); } File.Delete(path + "txt"); } } } }
private static void BackupFolder() { // create zip file using current date using (FileStream zipToOpen = File.Open(DateTime.Now.ToString() + Directory.GetCurrentDirectory() + ".zip", FileMode.Create)) { // create archive using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)) { // get list of files to be zipped, using current directory var fileList = Directory.GetFiles((Directory.GetCurrentDirectory())); // loop through each file in current directory and zip foreach (var file in fileList) { archive.CreateEntryFromFile(file, file); } // back up new zip file to folder // FINISH - REPLACE NAME WITH NAME OF BACKUP DIRECTORY? NOW USING MSDN STRING NAME archive.ExtractToDirectory(Directory.GetCurrentDirectory()); } } }
public override bool Execute() { try { if (File.Exists(DestinationArchive)) { if (OverwriteDestination == true) { Log.LogMessage(MessageImportance.Low, "{0} already existed, deleting before zipping...", DestinationArchive); File.Delete(DestinationArchive); } else { Log.LogWarning("'{0}' already exists. Did you forget to set '{1}' to true?", DestinationArchive, nameof(OverwriteDestination)); } } Log.LogMessage(MessageImportance.High, "Compressing {0} into {1}...", SourceDirectory, DestinationArchive); if (!Directory.Exists(Path.GetDirectoryName(DestinationArchive))) Directory.CreateDirectory(Path.GetDirectoryName(DestinationArchive)); if (ExcludePatterns == null) { ZipFile.CreateFromDirectory(SourceDirectory, DestinationArchive, CompressionLevel.Optimal, IncludeBaseDirectory); } else { // convert to regular expressions Regex[] regexes = new Regex[ExcludePatterns.Length]; for (int i = 0; i < ExcludePatterns.Length; ++i) regexes[i] = new Regex(ExcludePatterns[i].ItemSpec, RegexOptions.IgnoreCase); using (FileStream writer = new FileStream(DestinationArchive, FileMode.CreateNew)) { using (ZipArchive zipFile = new ZipArchive(writer, ZipArchiveMode.Create)) { var files = Directory.GetFiles(SourceDirectory, "*", SearchOption.AllDirectories); foreach (var file in files) { // look for a match bool foundMatch = false; foreach (var regex in regexes) { if (regex.IsMatch(file)) { foundMatch = true; break; } } if (foundMatch) { Log.LogMessage(MessageImportance.Low, "Excluding {0} from archive.", file); continue; } var relativePath = MakeRelativePath(SourceDirectory, file); zipFile.CreateEntryFromFile(file, relativePath, CompressionLevel.Optimal); } } } } } catch (Exception e) { // We have 2 log calls because we want a nice error message but we also want to capture the callstack in the log. Log.LogError("An exception has occured while trying to compress '{0}' into '{1}'.", SourceDirectory, DestinationArchive); Log.LogMessage(MessageImportance.Low, e.ToString()); return false; } return true; }
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; }
/// <summary> /// Compress csv files transformed from current AlgoSeek file /// <param name="sourceFile">AlgoSeek file which we extract data from</param> /// </summary> private static void CompressLeanCSV(FileInfo sourceFile) { var fileinfo = sourceFile.Name.Split('.'); var csvFilesFolders = new List<DirectoryInfo>(); new DirectoryInfo(_destinationDirectory + @"\" + _resolution + @"\" + fileinfo[0].ToLower()).GetDirectories() .ToList().ForEach(optionType => csvFilesFolders.AddRange(optionType.GetDirectories().ToList())); foreach (var csvFilesFolder in csvFilesFolders) { foreach (var ticktype in new string[] { "quote", "trade" }) { var zipfile = csvFilesFolder.FullName + @"\" + fileinfo[1] + "_" + ticktype + ".zip"; using (var z = new FileStream(zipfile, FileMode.Create)) using (var a = new ZipArchive(z, ZipArchiveMode.Create, true)) { var csvFiles = csvFilesFolder.GetFiles(fileinfo[1] + "*_" + ticktype + ".csv"); if (csvFiles.Length == 0) Console.WriteLine("No " + ticktype + " csv file to zip."); foreach (var csvFile in csvFiles) { a.CreateEntryFromFile(csvFile.FullName, csvFile.Name, CompressionLevel.Optimal); csvFile.Delete(); } } } } }
void ProcessDir(string distDir, string currentDir, ZipArchive archive, string targetName) { DirectoryInfo dir = new DirectoryInfo(distDir + currentDir + "\\"); foreach(FileInfo f in dir.GetFiles()) { archive.CreateEntryFromFile(f.FullName, targetName+"/" +currentDir+"/" + f.Name, CompressionLevel.Optimal); } foreach (DirectoryInfo d in dir.GetDirectories()) { ProcessDir(distDir, currentDir + "/" + d.Name, archive, targetName); } }
public static int Main(string[] args) { Stopwatch s = Stopwatch.StartNew(); var qts = FindQt(); bool found = qts.Count != 0; bool debug = false; QtInfo qt; if (!found) { qt = new QtInfo(); var result = ParseArgs(args, out qt.QMake, out qt.Make, out debug); if (result != 0) return result; } else { // TODO: Only for OSX for now, generalize for all platforms. qt = qts.Last(); } bool log = false; ConsoleLogger logredirect = log ? new ConsoleLogger() : null; if (logredirect != null) logredirect.CreateLogDirectory(); if (!QueryQt(qt, debug)) return 1; for (int i = qt.LibFiles.Count - 1; i >= 0; i--) { var libFile = qt.LibFiles[i]; var libFileName = Path.GetFileNameWithoutExtension(libFile); if (Path.GetExtension(libFile) == ".exe" || // QtDeclarative is obsolete and at the same time its headers cause conflicts with its successor of QtQuick libFileName == "QtDeclarative" || libFileName == "Qt5Declarative" || // QtQuickTest is a QML module but has 3 main C++ functions and is not auto-ignored libFileName == "QtQuickTest" || libFileName == "Qt5QuickTest") { qt.LibFiles.RemoveAt(i); } } var qtSharp = new QtSharp(qt); ConsoleDriver.Run(qtSharp); var wrappedModules = qtSharp.GetVerifiedWrappedModules(); ProcessGeneratedInlines(); if (wrappedModules.Count == 0) { Console.WriteLine("Generation failed."); return 1; } const string qtSharpZip = "QtSharp.zip"; if (File.Exists(qtSharpZip)) { File.Delete(qtSharpZip); } using (var zip = File.Create(qtSharpZip)) { using (var zipArchive = new ZipArchive(zip, ZipArchiveMode.Create)) { foreach (var wrappedModule in wrappedModules) { zipArchive.CreateEntryFromFile(wrappedModule.Key, wrappedModule.Key); var documentation = Path.ChangeExtension(wrappedModule.Key, "xml"); zipArchive.CreateEntryFromFile(documentation, documentation); zipArchive.CreateEntryFromFile(wrappedModule.Value, Path.GetFileName(wrappedModule.Value)); } zipArchive.CreateEntryFromFile("CppSharp.Runtime.dll", "CppSharp.Runtime.dll"); } } Console.WriteLine("Done in: " + s.Elapsed); return 0; }
public void Send() { Task.Run( () => { try { var apikey = "hVAAtCM7wCEaJe9DqlR52w"; var apiSecret = "haN4L38nqnyZTTfVyudb7WpR2vSAcOWB3PUEm6XQQ"; var subdomain = "hearthstonetracker"; var client = new Client(subdomain, apikey, apiSecret); object attachments = new object[] { }; if (AttachLog) { var logPath = Path.Combine((string)AppDomain.CurrentDomain.GetData("DataDirectory"), "logs"); var dirInfo = new DirectoryInfo(logPath); var latestLogfiles = dirInfo.GetFiles().Where(x => x.Extension == ".txt").OrderByDescending(x => x.LastWriteTime).Take(3).ToList(); if (latestLogfiles.Count > 0) { using (var ms = new MemoryStream()) { using (var zipfile = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var latestLogfile in latestLogfiles) { zipfile.CreateEntryFromFile(latestLogfile.FullName, latestLogfile.Name, CompressionLevel.Optimal); } } ms.Position = 0; var bytes = new Byte[ms.Length]; ms.Read(bytes, 0, bytes.Length); attachments = new object[] { new { name = "logfiles.zip", content_type = "application/zip", data = Convert.ToBase64String(bytes) } }; } } } var ticket = new { email = Email, ticket = new { state = "open", subject = Subject, message = Message, user_agent = "HearthstoneTracker App", attachments } }; client.Post("/api/v1/tickets.json", ticket); } catch (Exception ex) { Log.Error(ex); } }); TryClose(); MessageBox.Show("Your support request has been sent.", "Support request sent.", MessageBoxButton.OK); }
private bool CompressFiles() { if (string.IsNullOrEmpty(BaseDirectory)) { Log.LogError($"Missing value for required parameter {nameof(BaseDirectory)}"); return(false); } var workDir = FileHelpers.EnsureTrailingSlash(BaseDirectory).Replace('\\', '/'); foreach (var file in SourceFiles) { if (!string.IsNullOrEmpty(file.GetMetadata("Link"))) { continue; } var filePath = file.ItemSpec.Replace('\\', '/'); if (!filePath.StartsWith(workDir)) { Log.LogError("Item {0} is not inside the working directory {1}. Set the metadata 'Link' to file path that should be used within the zip archive", filePath, workDir); return(false); } file.SetMetadata("Link", filePath.Substring(workDir.Length)); } Directory.CreateDirectory(Path.GetDirectoryName(OutputPath)); using (var stream = IOFile.Create(OutputPath)) using (var zip = new ZipArchiveStream(stream, ZipArchiveMode.Create)) { foreach (var file in SourceFiles) { var entryName = file.GetMetadata("Link").Replace('\\', '/'); if (string.IsNullOrEmpty(Path.GetFileName(entryName))) { Log.LogError("Empty file names not allowed. The effective entry path for item '{0}' is '{1}'", file.ItemSpec, entryName); return(false); } var entry = zip.CreateEntryFromFile(file.ItemSpec, entryName); #if NET45 #elif NETCOREAPP2_0 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // This isn't required when creating a zip on Windows. unzip will check which // platform was used to create the zip file. If the zip was created on Windows, // unzip will use a default set of permissions. However, if the zip was created // on a Unix-y system, it will set the permissions as defined in the external_attr // field. // Set the file permissions on each entry so they are extracted correctly on Unix. // Picking -rw-rw-r-- by default because we don't yet have a good way to access existing // Unix permissions. If we don't set this, files may be extracted as ---------- (0000), // which means the files are completely unusable. // FYI - this may not be necessary in future versions of .NET Core. See https://github.com/dotnet/corefx/issues/17342. const int rw_rw_r = (0x8000 + 0x0100 + 0x0080 + 0x0020 + 0x0010 + 0x0004) << 16; entry.ExternalAttributes = rw_rw_r; } #else #error Update target frameworks #endif Log.LogMessage("Added '{0}' to archive", entry.FullName); } } var fileInfo = new FileInfo(OutputPath); Log.LogMessage(MessageImportance.High, $"Added {SourceFiles.Length} file(s) to '{OutputPath}' ({fileInfo.Length / 1024:n0} KB)"); return(true); }
public virtual IEnumerable<string> ExportTemplate(bool includeNuGetPackages) { foreach (var project in _dte.Solution.AllProjects()) { yield return ExportTemplate(project.Name, includeNuGetPackages); } var zipPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "My Exported Templates", "SolutionItems.zip"); using (FileStream zipToOpen = new FileStream(zipPath, FileMode.CreateNew)) using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { string solutionPath = Path.GetDirectoryName(_dte.Solution.FullName); foreach (var solutionItem in _dte.Solution.SolutionItems()) { string sourceFile; string entryName; if (solutionItem.ContainingProject.Name.Equals("Solution Items")) { sourceFile = Path.Combine(solutionPath, solutionItem.Name); entryName = solutionItem.Name; } else { sourceFile = Path.Combine(solutionPath, solutionItem.ContainingProject.Name, solutionItem.Name); entryName = Path.Combine(solutionItem.ContainingProject.Name, solutionItem.Name); } archive.CreateEntryFromFile(sourceFile, entryName); } } yield return zipPath; }
public string CompressDirectory(string path, Matcher matcher, IProgress<string> progress, CancellationToken ct) { string zipFilePath = Path.GetTempFileName(); using (FileStream zipStream = new FileStream(zipFilePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) { Queue<string> dirs = new Queue<string>(); dirs.Enqueue(path); while (dirs.Count > 0) { var dir = dirs.Dequeue(); var subdirs = Directory.GetDirectories(dir); foreach(var subdir in subdirs) { dirs.Enqueue(subdir); } var files = matcher.GetResultsInFullPath(dir); foreach (var file in files) { if (ct.IsCancellationRequested) { return string.Empty; } progress?.Report(file); string entryName = file.MakeRelativePath(dir).Replace('\\', '/'); archive.CreateEntryFromFile(file, entryName); } } } return zipFilePath; }
public string CompressFiles(IEnumerable<string> paths, string relativeTodir, IProgress<string> progress, CancellationToken ct) { string zipFilePath = Path.GetTempFileName(); using (FileStream zipStream = new FileStream(zipFilePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) { foreach(string path in paths) { string entryName = null; if (!string.IsNullOrWhiteSpace(relativeTodir)) { entryName = path.MakeRelativePath(relativeTodir).Replace('\\', '/'); } else { entryName = path.MakeRelativePath(Path.GetDirectoryName(path)).Replace('\\', '/'); } progress?.Report(path); archive.CreateEntryFromFile(path, entryName); } } return zipFilePath; }
/// <summary> /// Updates the file. /// </summary> /// <param name="zipArchive">The zip archive.</param> /// <param name="zipArchiveEntry">The zip archive entry.</param> /// <param name="fullName">The full name.</param> /// <param name="newFilePath">The new file path.</param> internal void UpdateFile( ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry, string fullName, string newFilePath) { TraceService.WriteLine("ZipperService::UpdateFile fullName=" + fullName); FileInfoBase fileInfoBase = this.fileSystem.FileInfo.FromFileName(fullName); FileInfoBase newFileInfoBase = this.fileSystem.FileInfo.FromFileName(newFilePath); if (newFileInfoBase.LastWriteTime > fileInfoBase.LastWriteTime) { //// delete the current one! zipArchiveEntry.Delete(); //// and now add the new one! zipArchive.CreateEntryFromFile(newFilePath, fullName); TraceService.WriteLine(zipArchiveEntry.Name + " has been replaced"); } else { TraceService.WriteLine(zipArchiveEntry.Name + " has not been replaced"); } }
/* Méthode qui permet de prendre l'ensemble du contenu d'un dossier sur le disque disque et le * stocker au format .zip dans un dossier archives du container */ public string ZipDirectory(string Folder) { string messageSortie = "Compression du Dossier : "; FileInfo zipFile = new FileInfo(Folder + ".zip"); try { // On liste tous les fichiers dans le dossier cible du disque string[] filePaths = Directory.GetFiles(Folder); // On cree un flux à l'aide de Fileinfo FileStream fs = zipFile.Create(); using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Create)) { foreach (string fileName in filePaths) { zip.CreateEntryFromFile(fileName, Path.GetFileName(fileName), CompressionLevel.Optimal); } } CloudBlockBlob blob = blobManager.container.GetDirectoryReference("archives").GetBlockBlobReference(zipFile.Name); using (FileStream fs2 = zipFile.OpenRead()) { blob.UploadFromStream(fs2); } }catch(System.IO.DirectoryNotFoundException) { messageSortie = "Erreur en spécifiant le Path du fichier : "; } return messageSortie + zipFile.Name; }
private static void WriteZipFile() { using (FileStream zipToOpen = File.Open(@"compressed.zip", FileMode.Create)) // this mode overwrites an exisiting file { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { ZipArchiveEntry readmeEntry = archive.CreateEntry("hi.txt"); using (StreamWriter writer = new StreamWriter(readmeEntry.Open())) { writer.WriteLine("Hi Mom!"); writer.WriteLine("========================"); } archive.CreateEntryFromFile("quotes.txt", "quotes.txt"); archive.CreateEntry("me").Open(); } } }
static void ProcessFolder(XElement folder, ZipArchive theZip, string folderRelativePath) { string targetDirectory = (string)folder.Attribute("Name"); string currentRelativePath = AppendRelativePath(folderRelativePath, targetDirectory); Console.WriteLine("Processing folder " + currentRelativePath); foreach (var component in folder.Elements(Namespace + ElementNameComponent)) { foreach (var file in component.Elements(Namespace + ElementNameFile)) { string source = (string)file.Attribute("Source"); string name = (string)file.Attribute("Name"); theZip.CreateEntryFromFile(RelativePathToolToSetupFolder + source, AppendRelativePath(currentRelativePath, name), CompressionLevel.Optimal); } } foreach (var secondaryFolder in folder.Elements(Namespace + ElementNameDirectory)) { ProcessFolder(secondaryFolder, theZip, currentRelativePath); } }
private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { var selected = new List<object>(TileList.SelectedItems); var picker = new FileSavePicker(); picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}"; picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" }); var file = await picker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await FileIO.WriteTextAsync(file, ""); using (var stream = await file.OpenStreamForWriteAsync()) using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) { while (zip.Entries.Count > 0) { zip.Entries[0].Delete(); } using (var metaStream = zip.CreateEntry("tiles.json").Open()) using (var writer = new StreamWriter(metaStream)) { var array = new JsonArray(); selected.ForEachWithIndex<SecondaryTile>((item, index) => { var objet = new JsonObject(); objet.Add("Name", item.DisplayName); objet.Add("Arguments", item.Arguments); objet.Add("TileId", item.TileId); objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo); objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo); objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo); array.Add(objet); if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) { var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6)); zip.CreateEntryFromFile(path, item.TileId + "/normal"); } }); writer.WriteLine(array.Stringify()); } FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if(status == FileUpdateStatus.Complete) { var folder = await file.GetParentAsync(); await new MessageDialog("Speichern erfolgreich").ShowAsync(); } else { await new MessageDialog("Speichern fehlgeschlagen").ShowAsync(); } Debug.WriteLine(status); } } }
[Pure] // Even if we change the file system... private static string CreateAnalysisPackage(DirectoryInfo outputDir, List<Tuple<int, string>> paths, string[] commandLine) { var start = DateTime.Now; string zipFileName; try { Console.WriteLine("Creating the package".PrefixWithCurrentTime()); var mapping = new List<Tuple<string, string>>(); zipFileName = string.Format(@"{0}\{1}.{2}", outputDir.FullName, Path.GetRandomFileName(), "zip"); // Create the stream using(var zipFile = new FileStream(zipFileName, FileMode.CreateNew)) { // Create the archive using(var zipArchive = new ZipArchive(zipFile, ZipArchiveMode.Create)) { var added = new List<string>(); // TODO TODO TODO: Be smarter and avoid adding // Add all files and dirs foreach(var path in paths) { // It seems that the .zip format allows to insert the same format twice. // But we want to avoid it if(added.Contains(path.Item2)) { continue; } // We are not sure that all the paths in the options really exists in the path, so we'd better make sure it is the case if (File.Exists(path.Item2)) { // We should normalize with RemoveColomns as there is a bug in Windows Explorer unzip!!! zipArchive.CreateEntryFromFile(path.Item2, RemoveColomns(path.Item2), CompressionLevel.Fastest); added.Add(path.Item2); } else if (Directory.Exists(path.Item2)) { foreach (var fileInDir in Directory.GetFiles(path.Item2)) { if(added.Contains(fileInDir)) { continue; } // By some simple benchmark, it seems the Faster option is the better: it creates a slighter larger .zip but in less time that is not regained by coping things around the network // Benchmarks: // Build Size cp to CloudotServer // NoCompression 1.0s 114M 11.00s // Fastest 2.1s 26M 2.70 s // Optimal 4.0s 21M 2.25s // We should normalize with RemoveColomns as there is a bug in Windows Explorer unzip!!! zipArchive.CreateEntryFromFile(fileInDir, RemoveColomns(fileInDir), CompressionLevel.Fastest); added.Add(fileInDir); } } } // Add a text file with the analysis options var readme = zipArchive.CreateEntry(CloudotInstructionsFileName); using(var writer = new StreamWriter(readme.Open())) { writer.WriteLine("** Cloudot analysis package **"); writer.WriteLine("Created on {0} (Creation time {1})", start, DateTime.Now - start); writer.WriteLine("Original command line (length {0}):", commandLine.Length); foreach (var entry in commandLine) { writer.WriteLine(entry); } } } } } catch(Exception e) { Console.WriteLine("Error while creating the package. Exception of type {0}", e.GetType()); return null; } Console.WriteLine("[Debug] Package {0} created in {1}", zipFileName, DateTime.Now - start); return zipFileName; }