void AddFiles(string folder, string folderInArchive) { int count = 0; foreach (string fileName in Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly)) { var fi = new FileInfo(fileName); if ((fi.Attributes & FileAttributes.Hidden) != 0) { continue; } var archiveFileName = ArchiveNameForFile(fileName, folderInArchive); long index = -1; if (zip.ContainsEntry(archiveFileName, out index)) { var e = zip.First(x => x.FullName == archiveFileName); if (e.ModificationTime < fi.LastWriteTimeUtc) { zip.AddFile(fileName, archiveFileName); } } else { zip.AddFile(fileName, archiveFileName); } count++; if (count == ZipArchiveEx.ZipFlushLimit) { Flush(); count = 0; } } }
public void EnumerateSkipDeletedEntries(bool deleteFromExistingFile) { var ms = new MemoryStream(Encoding.UTF8.GetBytes(TEXT)); File.WriteAllText("file1.txt", "1111"); string filePath = Path.GetFullPath("file1.txt"); if (File.Exists("test-archive-write.zip")) { File.Delete("test-archive-write.zip"); } ZipArchive zip = null; try { zip = ZipArchive.Open("test-archive-write.zip", FileMode.CreateNew); ZipEntry e; e = zip.AddFile(filePath, "/path/ZipTestCopy1.exe"); e = zip.AddFile(filePath, "/path/ZipTestCopy2.exe"); var text = "Hello World"; e = zip.AddEntry("/data/foo1.txt", text, Encoding.UTF8, CompressionMethod.Store); e = zip.AddEntry("/data/foo2.txt", File.OpenRead(filePath), CompressionMethod.Store); if (deleteFromExistingFile) { zip.Close(); zip = ZipArchive.Open("test-archive-write.zip", FileMode.Open); } ValidateEnumeratedEntries(zip, "path/ZipTestCopy1.exe", "path/ZipTestCopy2.exe", "data/foo1.txt", "data/foo2.txt"); // Delete first zip.DeleteEntry("path/ZipTestCopy1.exe"); ValidateEnumeratedEntries(zip, "path/ZipTestCopy2.exe", "data/foo1.txt", "data/foo2.txt"); // Delete last zip.DeleteEntry("data/foo2.txt"); ValidateEnumeratedEntries(zip, "path/ZipTestCopy2.exe", "data/foo1.txt"); // Delete middle zip.DeleteEntry("path/ZipTestCopy2.exe"); ValidateEnumeratedEntries(zip, "data/foo1.txt"); // Delete all zip.DeleteEntry("data/foo1.txt"); ValidateEnumeratedEntries(zip); } finally { zip?.Dispose(); } }
private static void Build(string binDir, string mainBin, string packageFile, string postInstall, string postRemove, bool noLogo, bool noShortcuts, bool noWine) { Stopwatch watch = Stopwatch.StartNew(); if (!noLogo) { Console.WriteLine("-------------------------------"); Console.WriteLine("| UpTool2 package build tools |"); Console.WriteLine("-------------------------------"); Console.WriteLine(); Console.WriteLine($"Using version {Assembly.GetExecutingAssembly().GetName().Version}"); Console.WriteLine(); } Console.WriteLine("Parsing arguments..."); packageFile ??= Path.Combine(binDir, "package.zip"); if (File.Exists(packageFile)) { Console.WriteLine("Removing previous package..."); File.Delete(packageFile); } Console.WriteLine("Copying binary dir..."); using ZipArchive archive = ZipFile.Open(packageFile, ZipArchiveMode.Create); { archive.AddDirectory(binDir, "Data", new[] { ".xml", ".pdb" }, new[] { packageFile }); Console.WriteLine("Creating batch scripts..."); if (mainBin == "FIND_BIN") { string[] tmp = Directory.GetFiles(binDir, "*.exe"); if (tmp.Length > 0) { mainBin = Directory.GetFiles(binDir, "*.exe")[0]; } if (tmp.Length > 1) { Console.WriteLine( "Detected multiple EXEs. This is not recommended as all processes running in the app folder will need to be terminated for uninstall to succeed"); Console.WriteLine( "Please consider removing unnecessary EXEs or notify me that anyone is actually using this."); } } string programName = Path.GetFileNameWithoutExtension(mainBin); (string installBat, string removeBat) = BatchScripts.Create(!noShortcuts, mainBin, programName, postInstall, postRemove); archive.AddFile("Install.bat", installBat); archive.AddFile("Remove.bat", removeBat); ShScripts.Create(archive.AddFile, !noShortcuts, mainBin, programName, postInstall, postRemove, !noWine); } watch.Stop(); Console.WriteLine($"Completed package creation in {watch.Elapsed}"); Console.WriteLine($"Output file: {Path.GetFullPath(packageFile)}"); }
private void AddAssemblies(ZipArchive apk) { bool debug = _Debug; bool use_shared_runtime = String.Equals(UseSharedRuntime, "true", StringComparison.OrdinalIgnoreCase); foreach (ITaskItem assembly in ResolvedUserAssemblies) { // Add assembly apk.AddFile(assembly.ItemSpec, GetTargetDirectory(assembly.ItemSpec), compressionLevel: CompressionLevel.NoCompression); // Try to add config if exists var config = Path.ChangeExtension(assembly.ItemSpec, "dll.config"); AddAssemblyConfigEntry(apk, config); // Try to add symbols if Debug if (debug) { var symbols = Path.ChangeExtension(assembly.ItemSpec, "dll.mdb"); if (File.Exists(symbols)) { apk.AddFile(symbols, "assemblies", compressionLevel: CompressionLevel.NoCompression); } } } if (use_shared_runtime) { return; } // Add framework assemblies foreach (ITaskItem assembly in ResolvedFrameworkAssemblies) { apk.AddFile(assembly.ItemSpec, "assemblies", compressionLevel: CompressionLevel.NoCompression); var config = Path.ChangeExtension(assembly.ItemSpec, "dll.config"); AddAssemblyConfigEntry(apk, config); // Try to add symbols if Debug if (debug) { var symbols = Path.ChangeExtension(assembly.ItemSpec, "dll.mdb"); if (File.Exists(symbols)) { apk.AddFile(symbols, "assemblies", compressionLevel: CompressionLevel.NoCompression); } } } }
public IActionResult GetDockerLogsZip() { using (_tracer.Step("DiagnosticsController.GetDockerLogsZip")) { // Also search for "today's" files in sub folders. Windows containers archives log files // when they reach a certain size. var currentDockerLogFilenames = GetCurrentDockerLogFilenames(SearchOption.AllDirectories); return(new FileCallbackResult("application/zip", (outputStream, _) => { using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: false)) { foreach (var filename in currentDockerLogFilenames) { zip.AddFile(filename, _tracer); } } return Task.CompletedTask; }) { FileDownloadName = String.Format("dockerlogs-{0:MM-dd-HH-mm-ss}.zip", DateTime.UtcNow) }); } }
protected override Task <HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfo info, string localFilePath) { HttpResponseMessage response = Request.CreateResponse(); using (var ms = new MemoryStream()) { using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) { foreach (FileSystemInfo fileSysInfo in info.EnumerateFileSystemInfos()) { DirectoryInfo directoryInfo = fileSysInfo as DirectoryInfo; if (directoryInfo != null) { zip.AddDirectory(new DirectoryInfoWrapper(directoryInfo), fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, String.Empty); } } } response.Content = ms.AsContent(); } response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar" response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip"; return(Task.FromResult(response)); }
/// <summary> /// Creates a csproj file and adds it to the passed in ZipArchive /// The csproj contain references to the core SDK, Http trigger, and build task /// it also contain 'Always' copy entries for all the files that are in wwwroot. /// </summary> /// <param name="zip"><see cref="ZipArchive"/> to add csproj file to.</param> /// <param name="files"><see cref="IEnumerable{ZipArchiveEntry}"/> of entries in the zip file to include in the csproj.</param> /// <param name="projectName">the {projectName}.csproj</param> private static ZipArchiveEntry AddCsprojFile(ZipArchive zip, IEnumerable <ZipArchiveEntry> files, string projectName) { // TODO different template for functionv2 // TODO download git repository when read only const string microsoftNETSdkFunctionsVersion = "1.0.8"; var csprojFile = new StringBuilder(); csprojFile.AppendLine( $@"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net461</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include=""Microsoft.NET.Sdk.Functions"" Version=""{microsoftNETSdkFunctionsVersion}"" /> </ItemGroup> <ItemGroup> <Reference Include=""Microsoft.CSharp"" /> </ItemGroup>"); csprojFile.AppendLine(" <ItemGroup>"); foreach (var entry in files) { csprojFile.AppendLine( $@" <None Update=""{entry.FullName}""> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None>"); } csprojFile.AppendLine(" </ItemGroup>"); csprojFile.AppendLine("</Project>"); return(zip.AddFile($"{projectName}.csproj", csprojFile.ToString())); }
public IActionResult Download([FromServices] IOptions <ScriptApplicationHostOptions> webHostOptions) { var path = webHostOptions.Value.ScriptPath; var dirInfo = FileUtility.DirectoryInfoFromDirectoryName(path); return(new FileCallbackResult(new MediaTypeHeaderValue("application/octet-stream"), async(outputStream, _) => { using (var zipArchive = new ZipArchive(outputStream, ZipArchiveMode.Create)) { foreach (FileSystemInfoBase fileSysInfo in dirInfo.GetFileSystemInfos()) { if (fileSysInfo is DirectoryInfoBase directoryInfo) { await zipArchive.AddDirectory(directoryInfo, fileSysInfo.Name); } else { // Add it at the root of the zip await zipArchive.AddFile(fileSysInfo.FullName, string.Empty); } } } }) { FileDownloadName = (System.Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "functions") + ".zip" });
/// <summary> /// Creates a csproj file and adds it to the passed in ZipArchive /// The csproj contain references to the core SDK, Http trigger, and build task /// it also contain 'Always' copy entries for all the files that are in wwwroot. /// </summary> /// <param name="zip"><see cref="ZipArchive"/> to add csproj file to.</param> /// <param name="files"><see cref="IEnumerable{ZipArchiveEntry}"/> of entries in the zip file to include in the csproj.</param> /// <param name="projectName">the {projectName}.csproj</param> private static ZipArchiveEntry AddCsprojFile(ZipArchive zip, IEnumerable <ZipArchiveEntry> files, string projectName) { const string microsoftAzureWebJobsVersion = "2.1.0-beta1"; const string microsoftAzureWebJobsExtensionsHttpVersion = "1.0.0-beta1"; const string microsoftNETSdkFunctionsVersion = "1.0.0-alpha6"; var csprojFile = new StringBuilder(); csprojFile.AppendLine( $@"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net461</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include=""Microsoft.Azure.WebJobs"" Version=""{microsoftAzureWebJobsVersion}"" /> <PackageReference Include=""Microsoft.Azure.WebJobs.Extensions.Http"" Version=""{microsoftAzureWebJobsExtensionsHttpVersion}"" /> <PackageReference Include=""Microsoft.NET.Sdk.Functions"" Version=""{microsoftNETSdkFunctionsVersion}"" /> </ItemGroup> <ItemGroup> <Reference Include=""Microsoft.CSharp"" /> </ItemGroup>"); csprojFile.AppendLine(" <ItemGroup>"); foreach (var entry in files) { csprojFile.AppendLine( $@" <None Update=""{entry.FullName}""> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None>"); } csprojFile.AppendLine(" </ItemGroup>"); csprojFile.AppendLine("</Project>"); return(zip.AddFile($"{projectName}.csproj", csprojFile.ToString())); }
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); }
protected override Task <IActionResult> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { if (!Request.Query.TryGetValue("fileName", out var fileName)) { fileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip"; } var result = new FileCallbackResult("application/zip", (outputStream, _) => { // Note that a stream wrapper is no longer needed for ZipArchive, this was fixed in its implementation. using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: false)) { foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { var directoryInfo = fileSysInfo as DirectoryInfoBase; if (directoryInfo != null) { zip.AddDirectory(directoryInfo, Tracer, fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, Tracer, String.Empty); } } } return(Task.CompletedTask); }) { FileDownloadName = fileName }; return(Task.FromResult((IActionResult)result)); }
private static void InternalAddDirectory(ZipArchive zipArchive, DirectoryInfoBase directory, ITracer tracer, string directoryNameInArchive, IList <ZipArchiveEntry> files = null) { bool any = false; foreach (var info in directory.GetFileSystemInfos()) { any = true; var subDirectoryInfo = info as DirectoryInfoBase; if (subDirectoryInfo != null) { string childName = ForwardSlashCombine(directoryNameInArchive, subDirectoryInfo.Name); InternalAddDirectory(zipArchive, subDirectoryInfo, tracer, childName, files); } else { var entry = zipArchive.AddFile((FileInfoBase)info, tracer, directoryNameInArchive); files?.Add(entry); } } if (!any) { // If the directory did not have any files or folders, add a entry for it zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive)); } }
public static void AddDirectory(this ZipArchive archive, string sourceDir) { DirectoryInfo directoryInfo = new DirectoryInfo(sourceDir); sourceDir = directoryInfo.FullName; foreach (FileSystemInfo entry in directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)) { string relativePath = entry.FullName.Substring(sourceDir.Length, entry.FullName.Length - sourceDir.Length); relativePath = relativePath.TrimStart(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); if (entry is FileInfo) { archive.AddFile(entry.FullName, relativePath); } else { DirectoryInfo subDirInfo = entry as DirectoryInfo; if (subDirInfo != null && !subDirInfo.EnumerateFileSystemInfos().Any()) { archive.CreateEntry(relativePath + Path.DirectorySeparatorChar); } } } }
public static void AddDirectory(this ZipArchive zipArchive, DirectoryInfoBase directory, ITracer tracer, string directoryNameInArchive) { bool any = false; foreach (var info in directory.GetFileSystemInfos()) { any = true; var subDirectoryInfo = info as DirectoryInfoBase; if (subDirectoryInfo != null) { string childName = ForwardSlashCombine(directoryNameInArchive, subDirectoryInfo.Name); zipArchive.AddDirectory(subDirectoryInfo, tracer, childName); } else { zipArchive.AddFile((FileInfoBase)info, tracer, directoryNameInArchive); } } if (!any) { // If the directory did not have any files or folders, add a entry for it zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive)); } }
public static void AddFile(this ZipArchive archive, string fileName, string zippedName, string zipRoot) { using (var stream = File.Open(fileName, FileMode.Open)) { archive.AddFile(zippedName, zipRoot, stream); } }
public static void AddFile(this ZipArchive archive, string fileName, string zippedName, string zipRoot) { using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { archive.AddFile(zippedName, zipRoot, stream); } }
void AddFileAndFlush(string filename, long fileLength, string archiveFileName, CompressionMethod compressionMethod) { filesWrittenTotalSize += fileLength; zip.AddFile(filename, archiveFileName, compressionMethod: compressionMethod); if ((filesWrittenTotalSize >= ZipArchiveEx.ZipFlushSizeLimit || filesWrittenTotalCount >= ZipArchiveEx.ZipFlushFilesLimit) && AutoFlush) { Flush(); } }
public static void AddFilesToZip(List <DaaSFileInfo> paths, ZipArchive zip) { foreach (var path in paths) { if (System.IO.File.Exists(path.FilePath)) { zip.AddFile(path.FilePath, path.Prefix, String.Empty); } } }
public void ArchiveFiles() { string[] sourcefiles = this.sourceFiles; using (ZipArchive archive = new ZipArchive()) { foreach (string file in sourcefiles) { archive.AddFile(file, "/"); } archive.Save("Documents\\ArchiveFiles.zip"); } }
public void CancelArchiveProgress() { string[] sourcefiles = this.sourceFiles; using (ZipArchive archive = new ZipArchive()) { archive.Progress += archive_Progress; foreach (string file in sourceFiles) { archive.AddFile(file, "/"); } archive.Save("Documents\\CancelArchiveProgress.zip"); } }
public void ArchiveWithComment() { string path = this.startupPath; using (ZipArchive archive = new ZipArchive()) { foreach (string file in System.IO.Directory.EnumerateFiles(path)) { ZipFileItem zipFI = archive.AddFile(file, "/"); zipFI.Comment = "Archived by " + Environment.UserName; } archive.Save("Documents\\ArchiveWithComment.zip"); } }
private void AddFilesToZip(ZipArchive zip) { foreach (var path in _paths) { if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); if (path.EndsWith(Constants.LogFilesPath, StringComparison.Ordinal)) { foreach (var info in dir.GetFileSystemInfos()) { var directoryInfo = info as DirectoryInfo; if (directoryInfo != null) { // excluding FREB as it contains user sensitive data such as authorization header if (!info.Name.StartsWith("W3SVC", StringComparison.OrdinalIgnoreCase)) { zip.AddDirectory(directoryInfo, _tracer, Path.Combine(dir.Name, info.Name)); } } else { zip.AddFile((FileInfo)info, _tracer, dir.Name); } } } else { zip.AddDirectory(dir, _tracer, Path.GetFileName(path)); } } // CORE TODO use filesystemhelper? else if (System.IO.File.Exists(path)) { zip.AddFile(path, _tracer, String.Empty); } } }
public static void AddDirectory(this ZipArchive archive, string folder, string folderInArchive) { string root = folderInArchive; foreach (var fileName in Directory.GetFiles(folder)) { archive.AddFile(fileName, root); } foreach (var dir in Directory.GetDirectories(folder)) { var internalDir = dir.Replace("./", string.Empty).Replace(folder, string.Empty); archive.AddDirectory(dir, folderInArchive + internalDir); } }
public static Stream CreateZip(IEnumerable <string> files, string rootPath) { var memoryStream = new MemoryStream(); using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, leaveOpen: true)) { foreach (var fileName in files) { zip.AddFile(fileName, fileName, rootPath); } } memoryStream.Seek(0, SeekOrigin.Begin); return(memoryStream); }
/// <summary> /// creates a local.settings.json file and populates it with the values in AppSettings /// The AppSettings are read from EnvVars with prefix APPSETTING_. /// local.settings.json looks like: /// { /// "IsEncrypted": true|false, /// "Values": { /// "Name": "Value" /// } /// } /// This method doesn't include Connection Strings. Unlike AppSettings, connection strings /// have 10 different prefixes depending on the type. /// </summary> /// <param name="zip"><see cref="ZipArchive"/> to add local.settings.json file to.</param> /// <returns></returns> private static ZipArchiveEntry AddAppSettingsFile(ZipArchive zip) { const string appSettingsPrefix = "APPSETTING_"; const string localAppSettingsFileName = "local.settings.json"; var appSettings = System.Environment.GetEnvironmentVariables() .Cast <DictionaryEntry>() .Where(p => p.Key.ToString().StartsWith(appSettingsPrefix, StringComparison.OrdinalIgnoreCase)) .ToDictionary(k => k.Key.ToString().Substring(appSettingsPrefix.Length), v => v.Value); var localSettings = JsonConvert.SerializeObject(new { IsEncrypted = false, Values = appSettings }, Formatting.Indented); return(zip.AddFile(localAppSettingsFileName, localSettings)); }
public IActionResult GetDeploymentScript() { using (_tracer.Step("DeploymentService.GetDeploymentScript")) { if (!_deploymentManager.GetResults().Any()) { return(NotFound("Need to deploy website to get deployment script.")); } string deploymentScriptContent = _deploymentManager.GetDeploymentScriptContent(); if (deploymentScriptContent == null) { return(NotFound("Operation only supported if not using a custom deployment script")); } var result = new FileCallbackResult("application/zip", (outputStream, _) => { using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: false)) { // Add deploy.cmd to zip file zip.AddFile(DeploymentManager.DeploymentScriptFileName, deploymentScriptContent); // Add .deployment to cmd file zip.AddFile(DeploymentSettingsProvider.DeployConfigFile, "[config]\ncommand = {0}\n".FormatInvariant(DeploymentManager.DeploymentScriptFileName)); } return(Task.CompletedTask); }) { FileDownloadName = "deploymentscript.zip" }; return(result); } }
public void ProtectPassword() { string[] sourcefiles = this.sourceFiles; string password = "******"; using (ZipArchive archive = new ZipArchive()) { foreach (string file in sourceFiles) { ZipFileItem zipFI = archive.AddFile(file, "/"); zipFI.EncryptionType = EncryptionType.Aes128; zipFI.Password = password; } archive.Save("Documents\\ProtectPassword.zip"); } }
public static Stream CreateZip(IEnumerable <string> files, string rootPath) { const int defaultBufferSize = 4096; var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, defaultBufferSize, FileOptions.DeleteOnClose); using (var zip = new ZipArchive(fileStream, ZipArchiveMode.Create, leaveOpen: true)) { foreach (var fileName in files) { zip.AddFile(fileName, fileName, rootPath); } } fileStream.Seek(0, SeekOrigin.Begin); return(fileStream); }
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, Mock.Of <ITracer>(), ""); // Assert zip.Dispose(); zip = new ZipArchive(ReOpen(stream)); Assert.Equal(1, zip.Entries.Count); AssertZipEntry(zip, fileName, content); }
public static void AddDirectory(this ZipArchive zip, string dir, string basePath = null) { var zipPath = string.IsNullOrEmpty(basePath) ? Path.GetFileName(dir) : basePath + "/" + Path.GetFileName(dir); foreach (var subFile in Directory.GetFiles(dir)) { zip.AddFile(subFile, zipPath); } foreach (var subDir in Directory.GetDirectories(dir)) { zip.AddDirectory(subDir, zipPath); } }
// This is the Zip Implementation Method partial void Zip(NSObject sender) { // Get the current working directory and set the desired name of the Zip File string path = Environment.CurrentDirectory; string fileName = "/file.zip"; theZipFile = path + fileName; // Create a new instance of ZipArchive ZipArchive zip = new ZipArchive(); // You can subscribe to OnError event so you can handle // any errors situations zip.OnError += (object s, EventArgs e) => { string error = s as String; Console.WriteLine("Error:" + error); }; // Create the Zip file on the desired path zip.CreateZipFile(theZipFile); // Add the files you want zip, this will return "true" if // the file was successfully added to zip file bool added = zip.AddFile(path + "/xamarin.jpg", "xamarin.jpg"); // Dont forget to close the zip file zip.CloseZipFile(); if(added) new UIAlertView("Info", "Success: " + theZipFile, null, "Great", null).Show(); else new UIAlertView("Info", "Something went wrong", null, "Ok", null).Show(); Console.WriteLine(theZipFile); }