public void AddDirectoryToArchiveIncludesDirectoryTreeInArchive() { // Arrange var stream = new MemoryStream(); var zip = new ZipArchive(stream, ZipArchiveMode.Create); var emptyDir = new Mock<DirectoryInfoBase>(); emptyDir.SetupGet(d => d.Name).Returns("empty-dir"); emptyDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[0]); var subDir = new Mock<DirectoryInfoBase>(); subDir.SetupGet(d => d.Name).Returns("site"); subDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { emptyDir.Object, CreateFile("home.aspx", "home content"), CreateFile("site.css", "some css") }); var directoryInfo = new Mock<DirectoryInfoBase>(); directoryInfo.SetupGet(f => f.Name).Returns("zip-test"); directoryInfo.Setup(f => f.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { subDir.Object, CreateFile("zero-length-file", ""), CreateFile("log.txt", "log content") }); // Act zip.AddDirectory(directoryInfo.Object, ""); // Assert zip.Dispose(); File.WriteAllBytes(@"d:\foo.zip", stream.ToArray()); zip = new ZipArchive(ReOpen(stream)); Assert.Equal(5, zip.Entries.Count); AssertZipEntry(zip, "log.txt", "log content"); AssertZipEntry(zip, @"site\home.aspx", "home content"); AssertZipEntry(zip, @"site\site.css", "some css"); AssertZipEntry(zip, @"site\empty-dir\", null); AssertZipEntry(zip, @"zero-length-file", null); }
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); }
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)); } } else if (File.Exists(path)) { zip.AddFile(path, _tracer, String.Empty); } } }
/// <summary>从目录创建压缩文档</summary> /// <param name="sourceDirectoryName"></param> /// <param name="destinationArchiveFileName"></param> /// <param name="compressionLevel"></param> /// <param name="includeBaseDirectory"></param> public static void CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, CompressionLevel compressionLevel, Boolean includeBaseDirectory) { if (String.IsNullOrEmpty(sourceDirectoryName)) { throw new ArgumentNullException(nameof(sourceDirectoryName)); } if (String.IsNullOrEmpty(destinationArchiveFileName)) { destinationArchiveFileName = Path.ChangeExtension(Path.GetFileName(destinationArchiveFileName), ".zip"); } using var zf = new ZipArchive(); zf.AddDirectory(sourceDirectoryName, null, compressionLevel == CompressionLevel.NoCompression); zf.Write(destinationArchiveFileName); }
/// <summary>快速压缩目录。</summary> /// <param name="dirName"></param> /// <param name="outputName"></param> public static void CompressDirectory(String dirName, String outputName = null) { if (String.IsNullOrEmpty(dirName)) { throw new ArgumentNullException(nameof(dirName)); } if (String.IsNullOrEmpty(outputName)) { outputName = Path.ChangeExtension(Path.GetFileName(dirName), ".zip"); } using var zf = new ZipArchive(); zf.AddDirectory(dirName); zf.Write(outputName); }
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 = PathHelper.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; }