/// <summary> /// Adds a directory to an archive recursively /// </summary> /// <param name="archive">The archive to add to</param> /// <param name="folderPath">The directory to add</param> /// <param name="entryName">The name of the directory in-archive</param> /// <param name="ignoredExtensions">Extensions for files to ignore</param> /// <param name="ignoredPaths">Paths to exclude from adding</param> /// <returns>The new entry</returns> public static ZipArchiveEntry AddDirectory(this ZipArchive archive, string folderPath, string entryName, string[] ignoredExtensions, string[] ignoredPaths) { entryName = entryName.TrimEnd('/'); ZipArchiveEntry result = archive.CreateEntry($"{entryName}/"); string[] files = Directory.GetFiles(folderPath); foreach (string t in files) { if (!ignoredExtensions.Contains(Path.GetExtension(t)) && !ignoredPaths.Any(s => IO.CheckPathEqual(s, t))) { archive.CreateEntryFromFile(t, $"{entryName}/{Path.GetFileName(t)}"); } } string[] dirs = Directory.GetDirectories(folderPath); foreach (string t in dirs) { if (!ignoredPaths.Any(s => IO.CheckPathEqual(s, t))) { archive.AddDirectory(t, $"{entryName}/{Path.GetFileName(t)}", ignoredExtensions, ignoredPaths); } } return(result); }
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(); 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); }
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" });
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)); } }
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)); }
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)); }
public override bool Execute() { Log.LogDebugMessage("EmbeddedNativeLibraries Task"); Log.LogDebugMessage(" OutputDirectory: {0}", OutputDirectory); Log.LogDebugTaskItems(" EmbeddedNativeLibraries:", EmbeddedNativeLibraries); var outDirInfo = new DirectoryInfo(OutputDirectory); // Copy files into _NativeLibraryImportsDirectoryName (native_library_imports) dir. if (!outDirInfo.Exists) { outDirInfo.Create(); } foreach (var lib in EmbeddedNativeLibraries) { // seealso bug #3477 to find out why we use this method. var abi = MonoAndroidHelper.GetNativeLibraryAbi(lib); if (abi == null) { Log.LogWarning( subcategory: string.Empty, warningCode: "XA4300", helpKeyword: string.Empty, file: lib.ItemSpec, lineNumber: 0, columnNumber: 0, endLineNumber: 0, endColumnNumber: 0, message: "Native library '{0}' will not be bundled because it has an unsupported ABI.", messageArgs: new [] { lib.ItemSpec, } ); continue; } if (!outDirInfo.GetDirectories(abi).Any()) { outDirInfo.CreateSubdirectory(abi); } MonoAndroidHelper.CopyIfChanged(lib.ItemSpec, Path.Combine(OutputDirectory, abi, Path.GetFileName(lib.ItemSpec))); } // Archive native libraries in a zip. using (var stream = new MemoryStream()) using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, true, new System.Text.UTF8Encoding(false))) { zip.AddDirectory(OutputDirectory, outDirInfo.Name); string outpath = Path.Combine(outDirInfo.Parent.FullName, "__AndroidNativeLibraries__.zip"); if (Files.ArchiveZip(outpath, f => { using (var fs = new FileStream(f, FileMode.CreateNew)) { stream.CopyTo(fs); } })) { Log.LogDebugMessage("Saving contents to " + outpath); } } return(true); }
public void ArchiveDirectory() { string path = this.startupPath; using (ZipArchive archive = new ZipArchive()) { archive.AddDirectory(path); archive.Save("Documents\\ArchiveDirectory.zip"); } }
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 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 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); } }
private void ZipPackage() { Assert.DirectoryExists(this.TempContentDirectory, "Unable to find request working directory."); string zipPath = Path.Combine(this.TempDirectory.FullName, this.Request.PackageZipName); this.OutputFile = new FileInfo(zipPath); Assert.FileDoesNotExist(this.OutputFile, "The package zip file already exists."); using (var fileStream = new FileStream(this.OutputFile.FullName, FileMode.CreateNew)) { using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) { var include = Settings.Default.PublishFileTypesIncludePattern.ToArray(); var exclude = Settings.Default.PublishFileTypesExcludePattern.ToArray(); archive.AddDirectory(this.TempContentDirectory, include, exclude); } } }
void CreateZip() { Console.WriteLine("creating zip file"); // Needed contents at ZipPath: // Files\Application\ --> All contents requied for Programm Files (x86)\Sharpkit\ // Files\NET\ --> the content of FrameworkDir\SharpKit // Files\NET_Unix\ --> only the modified files for unix. At this time, it will contain only the file SharpKit.Build.targets. // Files\Templates\ --> contains 'SharpKit Web Application.zip' and 'SharpKit 5 Web Application.zip' // Just copy the needed above files to @SourceFilesDir() and run this code. // @SourceFilesDir must be the parent directory of Files\ using (var zip = new ZipArchive(ZipPath) { AddFileCallback = t => Console.WriteLine(t) }) { zip.BeginUpdate(); zip.AddDirectory(SourceFilesDir); zip.EndUpdate(); } }
protected override async Task RunCore(CancellationTokenSource cancellationToken) { await Task.Run(() => { using (ZipArchive archive = new ZipArchive()) { archive.Progress += (s, e) => { DispatcherService.BeginInvoke(() => Progress = Math.Round(e.Progress * 100)); if (cancellationToken.IsCancellationRequested) { e.CanContinue = false; } }; if (!String.IsNullOrEmpty(Password)) { archive.Password = Password; archive.EncryptionType = EncryptionType.Aes256; } foreach (FileModel fileModel in FileModelList) { if (fileModel.IsDirectory) { archive.AddDirectory(fileModel.FullPath, fileModel.Name); } else { archive.AddFile(fileModel.FullPath, "/"); } } archive.Save(FilePath); } }); }
/// <summary> /// Populates a <see cref="ZipArchive"/> with the content of the function app. /// It can also include local.settings.json and .csproj files for a full Visual Studio project. /// sln file is not included since it changes between VS versions and VS can auto-generate it from the csproj. /// All existing functions are added as content with "Always" copy to output. /// </summary> /// <param name="zip">the <see cref="ZipArchive"/> to be populated with function app content.</param> /// <param name="includeAppSettings">Optional: indicates whether to add local.settings.json or not to the archive. Default is false.</param> /// <param name="includeCsproj">Optional: indicates whether to add a .csproj to the archive. Default is false.</param> /// <param name="projectName">Optional: the name for *.csproj file if <paramref name="includeCsproj"/> is true. Default is appName.</param> public void CreateArchive(ZipArchive zip, bool includeAppSettings = false, bool includeCsproj = false, string projectName = null) { var tracer = _traceFactory.GetTracer(); var directoryInfo = FileSystemHelpers.DirectoryInfoFromDirectoryName(_environment.FunctionsPath); // First add the entire wwwroot folder at the root of the zip. IList <ZipArchiveEntry> files; zip.AddDirectory(directoryInfo, tracer, string.Empty, out files); if (includeAppSettings) { // include local.settings.json if needed. files.Add(AddAppSettingsFile(zip)); } if (includeCsproj) { // include .csproj for Visual Studio if needed. projectName = projectName ?? ServerConfiguration.GetApplicationName(); AddCsprojFile(zip, files, projectName); } }
public override bool Execute() { if (LibraryProjectPropertiesFiles.Length == 0 && LibraryProjectZipFiles.Length == 0) { return(true); } Log.LogDebugMessage("CreateLibraryResourceArchive Task"); Log.LogDebugMessage(" OutputDirectory: {0}", OutputDirectory); Log.LogDebugMessage(" OutputJarsDirectory: {0}", OutputJarsDirectory); Log.LogDebugMessage(" OutputAnnotationsDirectory: {0}", OutputAnnotationsDirectory); Log.LogDebugMessage(" LibraryProjectProperties:"); foreach (var p in LibraryProjectPropertiesFiles) { Log.LogDebugMessage(" " + p.ItemSpec); } Log.LogDebugMessage(" LibraryProjectZip:"); foreach (var z in LibraryProjectZipFiles) { Log.LogDebugMessage(" " + z.ItemSpec); } var outDirInfo = new DirectoryInfo(OutputDirectory); // Copy files into _LibraryProjectImportsDirectoryName (library_project_imports) dir. if (!outDirInfo.Exists) { outDirInfo.Create(); } var projectsResolved = ResolveLibraryProjectReferences(LibraryProjectPropertiesFiles.Select(p => Path.GetFullPath(p.ItemSpec))); var imports = projectsResolved.Concat(LibraryProjectZipFiles.Select(p => p.ItemSpec)); foreach (var p in imports) { // note that imports could contain file name that neither of build items contains // (it may be one of those resolved references in project.properties). // Also non-zip files are now specified in full path. if (!LibraryProjectZipFiles.Any(l => l.ItemSpec == p)) { // project.properties var fileInfo = new FileInfo(p); if (!fileInfo.Exists) { throw new InvalidOperationException(String.Format("Library project properties file '{0}' does not exist.", p)); } var bindir = fileInfo.Directory.FullName; CopyLibraryContent(bindir, false); } else { // zip string tmpname = Path.Combine(Path.GetTempPath(), "monodroid_import_" + Guid.NewGuid().ToString()); try { Directory.CreateDirectory(tmpname); ZipFile.ExtractToDirectory(p, tmpname, new System.Text.UTF8Encoding(false)); if (!CopyLibraryContent(tmpname, p.EndsWith(".aar", StringComparison.OrdinalIgnoreCase))) { return(false); } } finally { Directory.Delete(tmpname, true); } } } // Archive them in a zip. using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, true, new System.Text.UTF8Encoding(false))) { zip.AddDirectory(OutputDirectory, outDirInfo.Name); } stream.Position = 0; string outpath = Path.Combine(outDirInfo.Parent.FullName, "__AndroidLibraryProjects__.zip"); if (Files.ArchiveZip(outpath, f => { using (var fs = new FileStream(f, FileMode.CreateNew)) { stream.CopyTo(fs); } })) { Log.LogDebugMessage("Saving contents to " + outpath); } } return(true); }
/// <summary> /// Saves the backup, determining whether the server is running (to backup a copy instead the original) or not /// </summary> /// <param name="isServerRunning">If the server is running, a temporary copy of itself will be created so no errors are thrown</param> /// <returns>True if the operation was successful</returns> public async Task <bool> Save(bool isServerRunning) { SetCreation(); bool success = true; await Task.Factory.StartNew(() => { var zipLocation = baseLocation + ".zip"; var bakLocation = baseLocation + fileExtension; try { if (!Directory.Exists(Path.GetDirectoryName(baseLocation))) { Directory.CreateDirectory(Path.GetDirectoryName(baseLocation)); } var folder = Server.Location; var folderName = Path.GetFileName(folder); // so we can perform the backup even with server running var tmpFolder = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()), folderName); if (Everything) { if (isServerRunning) // if the server is open, copy the server and then perform the backup { new DirectoryInfo(folder).CopyDirectory(new DirectoryInfo(tmpFolder)); ZipFile.CreateFromDirectory(tmpFolder, zipLocation); try { Directory.Delete(tmpFolder, true); } catch { }; } else // otherwise perform the backup directly { ZipFile.CreateFromDirectory(folder, zipLocation); } } else { using (ZipArchive zip = ZipFile.Open(zipLocation, ZipArchiveMode.Create)) { if (isServerRunning) { Directory.CreateDirectory(tmpFolder); // copy all the files and directories to a temporary location before adding them to the zip file foreach (var cfile in GetRequiredCopyFiles(folder)) { var tmpFile = Path.Combine(tmpFolder, Path.GetFileName(cfile)); File.Copy(cfile, tmpFile); zip.AddFile(tmpFile); } foreach (var cdir in GetRequiredCopyDirectories(folder)) { var tmpDir = Path.Combine(tmpFolder, Path.GetFileName(cdir)); new DirectoryInfo(cdir).CopyDirectory(new DirectoryInfo(tmpDir)); zip.AddDirectory(tmpDir); } // clear the temporary directory try { Directory.Delete(tmpFolder, true); } catch { }; } else { // if the server is closed, directly add all the files and directories to the zip foreach (var cfile in GetRequiredCopyFiles(folder)) { zip.AddFile(cfile); } foreach (var cdir in GetRequiredCopyDirectories(folder)) { zip.AddDirectory(cdir); } } } } // if we got this far, save the backup information Save(baseLocation + fileExtension); } catch // perhaps the server log is being used, or it doesn't exist; clear failed files { if (File.Exists(baseLocation + ".zip")) { try { File.Delete(baseLocation + ".zip"); } catch { } } success = false; } }); return(success); }
public static void PublishProject(string targetDir, bool includeSource, bool includeEditor, bool compress, bool createShortcuts, Func <string, bool> targetExistsCallback = null) { // Determine a valid directory name for the game string gameDirName = PathOp.GetValidFileName(DualityApp.AppData.AppName); string targetGameDir = Path.Combine(targetDir, gameDirName); string archiveBaseDir = targetGameDir; // If we're creating shortcuts, move everything into a distinct subfolder to hide it from the user if (createShortcuts) { targetGameDir = Path.Combine(targetGameDir, "GameData"); } // Make sure everything is saved before copying stuff DualityEditorApp.SaveAllProjectData(); // If the dynamically created target directory already exists, delete it. if (Directory.Exists(archiveBaseDir)) { bool empty = !Directory.EnumerateFiles(archiveBaseDir).Any(); if (!empty && targetExistsCallback == null) { throw new ArgumentException("The target directory already contains a non-empty folder named '" + gameDirName + "'.", "targetDir"); } else if (empty || targetExistsCallback(archiveBaseDir)) { Directory.Delete(archiveBaseDir, true); } else { return; } } // Create the target directories Directory.CreateDirectory(archiveBaseDir); Directory.CreateDirectory(targetGameDir); // Copy files to the target directory PathHelper.CopyDirectory(Environment.CurrentDirectory, targetGameDir, true, delegate(string path) { string matchPath = Path.Combine(".", PathHelper.MakeFilePathRelative(path)); // Exclude hidden files and folders if (!PathHelper.IsPathVisible(path)) { string fileName = Path.GetFileName(path); if (!string.Equals(fileName, "desktop.ini", StringComparison.InvariantCultureIgnoreCase) && !string.Equals(fileName, "WorkingFolderIcon.ico", StringComparison.InvariantCultureIgnoreCase)) { return(false); } } // Exclude temporary files if (RegExTemporaryProjectFiles.Any(entry => entry.IsMatch(matchPath))) { return(false); } else if (!includeSource && RegExSourcePathBlacklist.Any(entry => entry.IsMatch(matchPath))) { return(false); } else if (!includeEditor && RegExEditorPathBlacklist.Any(entry => entry.IsMatch(matchPath))) { return(false); } return(true); }); // Create shortcuts when requested if (createShortcuts) { // Create the shortcut to the game string shortcutFilePath = Path.Combine(archiveBaseDir, gameDirName + ".bat"); File.WriteAllText( shortcutFilePath, "cd GameData && start " + PathHelper.MakeFilePathRelative(DualityEditorApp.LauncherAppPath)); // Create a shortcut to the editor if (includeEditor) { File.WriteAllText( Path.Combine(archiveBaseDir, gameDirName + " Editor.bat"), "cd GameData && start DualityEditor.exe"); } } // Compress the directory if (compress) { string archivePath = Path.Combine(targetDir, gameDirName + ".zip"); using (FileStream archiveStream = File.Open(archivePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Create)) { archive.AddDirectory(archiveBaseDir); } Directory.Delete(archiveBaseDir, true); // Display compressed file to the user EditorHelper.ShowInExplorer(archivePath); } else { // Display directory to user EditorHelper.ShowInExplorer(targetGameDir); } return; }
public static void AddDirectory(this ZipArchive zipArchive, string directoryPath, ITracer tracer, string directoryNameInArchive = "") { var directoryInfo = new DirectoryInfoWrapper(new DirectoryInfo(directoryPath)); zipArchive.AddDirectory(directoryInfo, tracer, directoryNameInArchive); }
public override bool Execute() { if (IsApplication) { return(true); } Log.LogDebugMessage("CreateManagedLibraryResourceArchive Task"); Log.LogDebugMessage(" OutputDirectory: {0}", OutputDirectory); Log.LogDebugMessage(" ResourceDirectory: {0}", ResourceDirectory); Log.LogDebugTaskItems(" AndroidAssets:", AndroidAssets); Log.LogDebugTaskItems(" AndroidJavaSources:", AndroidJavaSources); Log.LogDebugTaskItems(" AndroidJavaLibraries:", AndroidJavaLibraries); var outDirInfo = new DirectoryInfo(OutputDirectory); // Copy files into _LibraryProjectImportsDirectoryName (library_project_imports) dir. if (!outDirInfo.Exists) { outDirInfo.Create(); } foreach (var sub in new string [] { "assets", "res", "java", "bin" }) { var subdirInfo = new DirectoryInfo(Path.Combine(outDirInfo.FullName, sub)); if (!subdirInfo.Exists) { subdirInfo.Create(); } } var dir_sep = new char [] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; if (AndroidAssets != null) { var dstsub = Path.Combine(outDirInfo.FullName, "assets"); if (!Directory.Exists(dstsub)) { Directory.CreateDirectory(dstsub); } foreach (var item in AndroidAssets) { var path = item.GetMetadata("Link"); path = !string.IsNullOrWhiteSpace(path) ? path : item.ItemSpec; var head = string.Join("\\", path.Split(dir_sep).TakeWhile(s => !s.Equals(MonoAndroidAssetsPrefix, StringComparison.OrdinalIgnoreCase))); path = head.Length == path.Length ? path : path.Substring((head.Length == 0 ? 0 : head.Length + Path.DirectorySeparatorChar) + MonoAndroidAssetsPrefix.Length).TrimStart(dir_sep); MonoAndroidHelper.CopyIfChanged(item.ItemSpec, Path.Combine(dstsub, path)); } } // resources folders are converted to the structure that aapt accepts. bool hasInvalidName = false; foreach (var srcsub in Directory.GetDirectories(ResourceDirectory)) { var dstsub = Path.Combine(outDirInfo.FullName, "res", Path.GetFileName(srcsub)); if (!Directory.Exists(dstsub)) { Directory.CreateDirectory(dstsub); } foreach (var file in Directory.GetFiles(srcsub)) { var filename = Path.GetFileName(file); MonoAndroidHelper.CopyIfChanged(file, Path.Combine(dstsub, Path.GetFileName(file))); } } if (hasInvalidName) { return(false); } if (AndroidJavaSources != null) { foreach (var item in AndroidJavaSources) { MonoAndroidHelper.CopyIfChanged(item.ItemSpec, Path.Combine(outDirInfo.FullName, item.ItemSpec)); } } if (AndroidJavaLibraries != null) { foreach (var item in AndroidJavaLibraries) { MonoAndroidHelper.CopyIfChanged(item.ItemSpec, Path.Combine(outDirInfo.FullName, item.ItemSpec)); } } var nameCaseMap = new StringWriter(); // add resource case mapping descriptor to the archive. if (AndroidResourcesInThisExactProject != null && AndroidResourcesInThisExactProject.Any()) { Log.LogMessage("writing __res_name_case_map.txt..."); foreach (var res in AndroidResourcesInThisExactProject) { nameCaseMap.WriteLine("{0};{1}", res.GetMetadata("LogicalName").Replace('\\', '/'), Path.Combine(Path.GetFileName(Path.GetDirectoryName(res.ItemSpec)), Path.GetFileName(res.ItemSpec)).Replace('\\', '/')); } File.WriteAllText(Path.Combine(OutputDirectory, "__res_name_case_map.txt"), nameCaseMap.ToString()); } // Archive them in a zip. using (var stream = new MemoryStream()) using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, true, new System.Text.UTF8Encoding(false))) { zip.AddDirectory(OutputDirectory, outDirInfo.Name); string outpath = Path.Combine(outDirInfo.Parent.FullName, "__AndroidLibraryProjects__.zip"); if (Files.ArchiveZip(outpath, f => { using (var fs = new FileStream(f, FileMode.CreateNew)) { stream.CopyTo(fs); } })) { Log.LogDebugMessage("Saving contents to " + outpath); } } return(true); }