private static void AddUpdateDeleteInventories(ZipArchiveEntry inventoriesEntry) { Console.WriteLine("inventories.csv is {0} bytes", inventoriesEntry.Length); IEnumerable<Inventory> inventories = null; using (var entryStream = inventoriesEntry.Open()) { Console.WriteLine("Starting inventories at {0:hh:mm:ss.fff}", DateTime.Now); var stopwatch = new Stopwatch(); stopwatch.Start(); var reader = new StreamReader(entryStream); var csv = new CsvReader(reader); csv.Configuration.RegisterClassMap(new InventoryMap()); StringBuilder invForImport = new StringBuilder(); inventories = csv.GetRecords<Inventory>().Where(i => !i.IsDead); var inventoryCollection = new InventoryCollection(); inventoryCollection.SetItems(inventories); var importer = new NpgsqlBulkImporter(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString, stopwatch); importer.BulkImport("inventories", inventoryCollection); stopwatch.Stop(); Console.WriteLine("Finished inventories at {0:hh:mm:ss.fff}, taking {1}", DateTime.Now, stopwatch.Elapsed); } }
private static bool AreHashEqual(FileInfo existing, ZipArchiveEntry duplicate) { byte[] originalHash; byte[] otherHash; try { using (FileStream original = File.Open(existing.FullName, FileMode.Open, FileAccess.Read)) { if (null == (originalHash = HashFile(original))) { return false; } } using (Stream other = duplicate.Open()) { if (null == (otherHash = HashFile(other))) { return false; } } if (originalHash.Length == otherHash.Length) { for (int index = 0; index < originalHash.Length; index++) { if (originalHash[index] != otherHash[index]) { WriteError("Hashes don't match."); return false; } } return true; } return false; } catch (Exception e) { WriteError("Error while trying to compare hash. Error {0}", e.Message); return false; } }
internal static string Process(ZipArchiveEntry packageFile, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { using (var stream = packageFile.Open()) { return Process(stream, msBuildNuGetProjectSystem, throwIfNotFound: false); } }
/// <summary> /// Reads a ZipArchive entry as the routes CSV and extracts the route colors. /// </summary> private static List<GoogleRoute> ParseRouteCSV(ZipArchiveEntry entry) { var routes = new List<GoogleRoute>(); using (var reader = new StreamReader(entry.Open())) { // Ignore the format line reader.ReadLine(); while (!reader.EndOfStream) { var parts = reader.ReadLine().Split(','); // Ignore all routes which aren't part of CTS and thus don't have any real-time data. if (parts[0].Contains("ATS") || parts[0].Contains("PC") || parts[0].Contains("LBL")) { continue; } routes.Add(new GoogleRoute(parts)); } } return routes; }
static void WriteZipArchiveEntry(ZipArchiveEntry entry, string toWrite) { using (StreamWriter writer = new StreamWriter(entry.Open())) { writer.Write(toWrite); } }
private static void AddUpdateDeleteStores(ZipArchiveEntry entry) { IEnumerable<Store> stores = null; using (var entryStream = entry.Open()) { Console.WriteLine("stores.csv is {0} bytes", entry.Length); Console.WriteLine("Starting stores at {0:hh:mm:ss.fff}", DateTime.Now); var storeTimer = new Stopwatch(); storeTimer.Start(); var reader = new StreamReader(entryStream); var csv = new CsvReader(reader); csv.Configuration.RegisterClassMap(new StoreMap()); stores = csv.GetRecords<Store>().Where(s => !s.IsDead); var storesCollection = new StoreCollection(); storesCollection.SetItems(stores); var importer = new NpgsqlBulkImporter(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString, storeTimer); importer.BulkImport("stores", storesCollection); using (var wrapper = new NpgsqlConnectionWrapper(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString)) { wrapper.Connection.Open(); var rowsGeoUpdated = wrapper.ExecuteNonQuery("update stores s set (location) = ((select ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) from stores ss where s.id = ss.id))"); Console.WriteLine($"Updated {rowsGeoUpdated} rows geo data from lat/long data"); } storeTimer.Stop(); Console.WriteLine("Finished stores at {0:hh:mm:ss.fff}, taking {1}", DateTime.Now, storeTimer.Elapsed); } }
public PackageEntry(ZipArchiveEntry zipArchiveEntry) { FullName = zipArchiveEntry.FullName; Name = zipArchiveEntry.Name; Length = zipArchiveEntry.Length; CompressedLength = zipArchiveEntry.CompressedLength; }
/// <summary> /// Builds the zip file. /// </summary> /// <param name="updatesDirectory">The updates directory.</param> /// <param name="folderName">Name of the folder.</param> /// <param name="zipArchive">The zip archive.</param> /// <param name="zipArchiveEntry">The zip archive entry.</param> public void BuildZipFile( string updatesDirectory, string folderName, ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry) { ////TraceService.WriteLine("ZipperService::BuildZipFile"); string fullName = zipArchiveEntry.FullName; ////TraceService.WriteLine("Processing " + fullName); if (fullName.ToLower().StartsWith(folderName.ToLower()) && fullName.ToLower().EndsWith(".dll")) { //// we have found one of the assemblies TraceService.WriteLine("Found assembley " + fullName); //// first look to see if we have a replacement string newFilePath = updatesDirectory + @"\" + zipArchiveEntry.Name; bool exists = this.fileSystem.File.Exists(newFilePath); if (exists) { this.UpdateFile(zipArchive, zipArchiveEntry, fullName, newFilePath); } else { TraceService.WriteLine(newFilePath + " does not exist"); } } }
private string ZipperExtractFileToPath(string destRootPath, System.IO.Compression.ZipArchiveEntry item) { var destFilename = CleanFilenameString(System.IO.Path.Combine(destRootPath, item.Name)); FileStorageHelper.DeleteFile(destFilename); FileStorageHelper.CreateDirectory(System.IO.Path.GetDirectoryName(destFilename)); // var count = 5; do { try { item.ExtractToFile(destFilename, true); if (System.IO.File.Exists(destFilename)) { var fileInfo = new System.IO.FileInfo(destFilename); fileInfo.LastWriteTime = DateTime.Now; } break; } catch { if (--count <= 0) { throw; } Threading.ThreadingHelper.Sleep(200); } } while (true); // return(destFilename); }
/// <summary> /// Unzips ZipArchiveEntry asynchronously. /// </summary> /// <param name="entry">The entry which needs to be unzipped</param> /// <param name="filePath">The entry's full name</param> /// <param name="unzipFolder">The unzip folder</param> /// <returns></returns> private static async Task UnzipZipArchiveEntryAsync(ZipArchiveEntry entry, string filePath, StorageFolder unzipFolder) { if (IfPathContainDirectory(filePath)) { // Create sub folder string subFolderName = Path.GetDirectoryName(filePath); bool isSubFolderExist = await IfFolderExistsAsync(unzipFolder, subFolderName); StorageFolder subFolder; if (!isSubFolderExist) { // Create the sub folder. subFolder = await unzipFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.ReplaceExisting); } else { // Just get the folder. subFolder = await unzipFolder.GetFolderAsync(subFolderName); } // All sub folders have been created yet. Just pass the file name to the Unzip function. string newFilePath = Path.GetFileName(filePath); if (!string.IsNullOrEmpty(newFilePath)) { // Unzip file iteratively. await UnzipZipArchiveEntryAsync(entry, newFilePath, subFolder); } } else { // Read uncompressed contents using (Stream entryStream = entry.Open()) { byte[] buffer = new byte[entry.Length]; entryStream.Read(buffer, 0, buffer.Length); // Create a file to store the contents StorageFile uncompressedFile = await unzipFolder.CreateFileAsync (entry.Name, CreationCollisionOption.ReplaceExisting); // Store the contents using (IRandomAccessStream uncompressedFileStream = await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite)) { using (Stream outstream = uncompressedFileStream.AsStreamForWrite()) { outstream.Write(buffer, 0, buffer.Length); outstream.Flush(); } } } } }
/// <summary> /// Constructor. /// </summary> public CompressedArchiveFile(ZipArchiveEntry entry, int stripInitialFolders) { if (!entry.IsFile()) throw new InvalidOperationException("Not a file."); _entry = entry; _stripInitialFolders = stripInitialFolders; }
private async Task Extract(ZipArchiveEntry entry, string basePath) { var fn = Path.Combine(basePath, entry.FullName); using (var fstream = File.Create(fn)) { await entry.Open().CopyToAsync(fstream); } }
private WrappedStream(Stream baseStream, Boolean closeBaseStream, ZipArchiveEntry entry, Action<ZipArchiveEntry> onClosed) { _baseStream = baseStream; _closeBaseStream = closeBaseStream; _onClosed = onClosed; _zipArchiveEntry = entry; _isDisposed = false; }
private void OnDoubleClick(object sender, MouseButtonEventArgs e) { var listBox = sender as ListBox; if (listBox.SelectedItem != null) { Result = listBox.SelectedItem as ZipArchiveEntry; Close(); } }
public ZipWrappingStream(ZipArchiveEntry zipArchiveEntry, Stream stream, FileMode packageFileMode, FileAccess packageFileAccess, bool canRead, bool canWrite) { _zipArchiveEntry = zipArchiveEntry; _baseStream = stream; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; _canRead = canRead; _canWrite = canWrite; }
// A specific constructor to allow decompression of Deflate64 internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); InitializeInflater(stream, false, null, method); }
/// <summary> /// Initializes a new instance of the <see cref="GedcomxFileEntry"/> class. /// </summary> /// <param name="entry">The zip archive this file belongs to.</param> /// <param name="attributes">The attributes belonging to this file (such as content type, etc).</param> /// <exception cref="System.ArgumentNullException">Thrown if the entry parameter is <c>null</c>.</exception> public GedcomxFileEntry(ZipArchiveEntry entry, List<ManifestAttribute> attributes) { if (entry == null) { throw new ArgumentNullException("entry"); } this.zipEntry = entry; this.attributes = attributes; }
private static void CopyStream(ZipArchiveEntry entry, MemoryStream ms) { var buffer = new byte[16*1024 - 1]; int read; var stream = entry.Open(); while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } }
/// <summary> /// Filters out the undesired entries from the copying process when calling CopyZipEntries method. /// </summary> /// <param name="entry">ZipArchiveEntry to filter.</param> /// <returns>True if entry should be included in the archive.</returns> private bool FilterNewXapContent(ZipArchiveEntry entry) { if (StringComparer.OrdinalIgnoreCase.Equals(entry.FullName, "AppManifest.xaml")) return false; if (_deletedEntries.Contains(entry.FullName)) return false; return true; }
public ArchiveFile(string abstractPath, ZipArchiveEntry entry) { // для работы с entry архив должен быть открыт в ArchiveDirectory в режиме Update _entry = entry; // path внутри архива AbstractPath = abstractPath; AbstractName = entry.Name; AbstractSize = entry.CompressedLength; DateOfLastAppeal = entry.LastWriteTime.DateTime.ToString(CultureInfo.InvariantCulture); }
public void TransformFile(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { // Get the xml fragment XElement xmlFragment = GetXml(packageFile, msBuildNuGetProjectSystem); XDocument transformDocument = XmlUtility.GetOrCreateDocument(xmlFragment.Name, targetPath, msBuildNuGetProjectSystem); // Do a merge transformDocument.Root.MergeWith(xmlFragment, _nodeActions); MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, transformDocument.Save); }
public ArchiveFile(string abstractPath, ZipArchiveEntry entry) { // для работы с entry архив должен быть открыт в ArchiveDirectory в режиме Update _entry = entry; // path внутри архива AbstractPath = abstractPath; AbstractName = entry.Name; AbstractSize = 0; DateOfCreation = ""; DateOfChange = ""; DateOfLastAppeal = ""; }
/// <summary> /// Constructs a ZipPackagePart for an atomic (i.e. non-interleaved) part. /// This is called from the ZipPackage class as a result of GetPartCore, /// GetPartsCore or CreatePartCore methods /// </summary> /// <param name="zipPackage"></param> /// <param name="zipArchive"></param> /// <param name="zipArchiveEntry"></param> /// <param name="zipStreamManager"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage zipPackage, ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry, ZipStreamManager zipStreamManager, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) : base(zipPackage, partUri, contentType, compressionOption) { _zipPackage = zipPackage; _zipArchive = zipArchive; _zipStreamManager = zipStreamManager; _zipArchiveEntry = zipArchiveEntry; }
private async Task Extract(ZipArchiveEntry entry, string basePath) { var fn = Path.Combine(basePath, entry.FullName); var dir = Path.GetDirectoryName(fn); if (dir == null) { throw new UpdateException("patch path is not valid."); } // ensure create directory Directory.CreateDirectory(dir); using (var fstream = File.Create(fn)) { await entry.Open().CopyToAsync(fstream); } }
void PrepareSection4Member(IEmdFileMember actualMember, ZipArchiveEntry item) { IEmdFileSection actSection = m_resEmdFileSection.Resolve(); actSection.Index = 0; actSection.Position = 0.0; actualMember.Sections.Add(actSection); actSection = m_resEmdFileSection.Resolve(); actSection.Index = 1; actSection.Position = 0.5; actualMember.Sections.Add(actSection); actSection = m_resEmdFileSection.Resolve(); actSection.Index = 2; actSection.Position = 1.0; actualMember.Sections.Add(actSection); }
private PackageManifest _TryGetPackageManifest(ZipArchiveEntry manifestEntry) { using (var reader = manifestEntry.Open()) using (var xmlReader = XmlReader.Create(reader, new XmlReaderSettings { Schemas = SchemaSets.PackageManifest })) { if (!mPackageManifestSerializer.CanDeserialize(xmlReader)) { return null; } return (PackageManifest)mPackageManifestSerializer.Deserialize(xmlReader); } }
public ZipEntryBlob(string name, ZipArchiveEntry entry) { #region Preconditions if (name == null) throw new ArgumentNullException(nameof(name)); if (entry == null) throw new ArgumentNullException(nameof(entry)); #endregion Name = name; this.entry = entry; }
private static async Task InflateEntryAsync(ZipArchiveEntry entry, StorageFolder destFolder, bool createSub = false) { string filePath = entry.FullName; if (!string.IsNullOrEmpty(filePath) && filePath.Contains("/") && !createSub) { // Create sub folder string subFolderName = Path.GetDirectoryName(filePath); StorageFolder subFolder; // Create or return the sub folder. subFolder = await destFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.OpenIfExists); string newFilePath = Path.GetFileName(filePath); if (!string.IsNullOrEmpty(newFilePath)) { // Unzip file iteratively. await InflateEntryAsync(entry, subFolder, true); } } else { // Read uncompressed contents using (Stream entryStream = entry.Open()) { byte[] buffer = new byte[entry.Length]; entryStream.Read(buffer, 0, buffer.Length); // Create a file to store the contents StorageFile uncompressedFile = await destFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting); // Store the contents using (IRandomAccessStream uncompressedFileStream = await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite)) { using (Stream outstream = uncompressedFileStream.AsStreamForWrite()) { outstream.Write(buffer, 0, buffer.Length); outstream.Flush(); } } } } }
/// <summary> /// Safely extracts a single file from a zip file /// </summary> /// <param name="file"> /// The zip entry we are pulling the file from /// </param> /// <param name="destinationPath"> /// The root of where the file is going /// </param> /// <param name="overwriteMethod"> /// Specifies how we are going to handle an existing file. /// The default is Overwrite.IfNewer. /// </param> public static void ImprovedExtractToFile(ZipArchiveEntry file, string destinationPath, Overwrite overwriteMethod = Overwrite.IfNewer) { //Gets the complete path for the destination file, including any //relative paths that were in the zip file string destinationFileName = Path.Combine(destinationPath, file.FullName); //Gets just the new path, minus the file name so we can create the //directory if it does not exist string destinationFilePath = Path.GetDirectoryName(destinationFileName); //Creates the directory (if it doesn't exist) for the new path Directory.CreateDirectory(destinationFilePath); //Determines what to do with the file based upon the //method of overwriting chosen switch (overwriteMethod) { case Overwrite.Always: //Just put the file in and overwrite anything that is found file.ExtractToFile(destinationFileName, true); break; case Overwrite.IfNewer: //Checks to see if the file exists, and if so, if it should //be overwritten if (!File.Exists(destinationFileName) || File.GetLastWriteTime(destinationFileName) < file.LastWriteTime) { //Either the file didn't exist or this file is newer, so //we will extract it and overwrite any existing file file.ExtractToFile(destinationFileName, true); } break; case Overwrite.Never: //Put the file in if it is new but ignores the //file if it already exists if (!File.Exists(destinationFileName)) { file.ExtractToFile(destinationFileName); } break; default: break; } }
protected void CreateFileZip() { string dirRoot = Server.MapPath("~/file"); //get a list of files string[] filesToZip = Directory.GetFiles(dirRoot, "*.*", SearchOption.AllDirectories); using (MemoryStream zipMS = new MemoryStream()) { using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(zipMS, System.IO.Compression.ZipArchiveMode.Create, true)) { //loop through files to add foreach (string fileToZip in filesToZip) { //exclude some files? -I don't want to ZIP other .zips in the folder. if (new FileInfo(fileToZip).Extension == ".zip") { continue; } //exclude some file names maybe? if (fileToZip.Contains("node_modules")) { continue; } //read the file bytes byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip); //create the entry - this is the zipped filename //change slashes - now it's VALID System.IO.Compression.ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Replace(dirRoot, "").Replace('\\', '/')); //add the file contents using (Stream zipEntryStream = zipFileEntry.Open()) using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream)) { zipFileBinary.Write(fileToZipBytes); } } } using (FileStream finalZipFileStream = new FileStream(Server.MapPath("~/file/DanhSachBangKe.zip"), FileMode.Create)) { zipMS.Seek(0, SeekOrigin.Begin); zipMS.CopyTo(finalZipFileStream); } } }
private ErrorSuccess<IVsixPackage, string> _CreateFromZipManifest(string file, ZipArchiveEntry manifestEntry, Logger log, ErrorSuccessFactory<IVsixPackage, string> ef) { var packageManifest = _TryGetPackageManifest(manifestEntry); var vsixManifest = _TryGetVsixManifest(manifestEntry); if (packageManifest != null) { log.Info("Loaded PackageManifest based manifest"); return ef.Success(new VsixWithPackageManifest(file, packageManifest)); } if (vsixManifest != null) { log.Info("Loaded Vsix based manifest"); return ef.Success(new VsixWithVsixManifest(file, vsixManifest)); } return ef.Error($"{file}\\{Entry.Manifest} is not a valid package manifest file."); }
private static void PerformXdtTransform(ZipArchiveEntry packageFile, string targetPath, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { if(FileSystemUtility.FileExists(msBuildNuGetProjectSystem.ProjectFullPath, targetPath)) { string content = Preprocessor.Process(packageFile, msBuildNuGetProjectSystem); try { using (var transformation = new XmlTransformation(content, isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument()) { document.PreserveWhitespace = true; // make sure we close the input stream immediately so that we can override // the file below when we save to it. using (var inputStream = File.OpenRead(FileSystemUtility.GetFullPath(msBuildNuGetProjectSystem.ProjectFullPath, targetPath))) { document.Load(inputStream); } bool succeeded = transformation.Apply(document); if (succeeded) { // save the result into a memoryStream first so that if there is any // exception during document.Save(), the original file won't be truncated. MSBuildNuGetProjectSystemUtility.AddFile(msBuildNuGetProjectSystem, targetPath, document.Save); } } } } catch (Exception exception) { throw new InvalidDataException( String.Format( CultureInfo.CurrentCulture, Strings.XdtError + " " + exception.Message, targetPath, msBuildNuGetProjectSystem.ProjectName), exception); } } }
public ZipArchiveEntryProgressInfo(ZipArchiveEntry entry, IReadOnlyList <ZipArchiveEntry> all) { ZipArchiveEntry = entry; All = all; }
/// <summary> /// Creates a file on the file system with the entry’s contents and the specified name. The last write time of the file is set to the /// entry’s last write time. This method does not allow overwriting of an existing file with the same name. Attempting to extract explicit /// directories (entries with names that end in directory separator characters) will not result in the creation of a directory. /// </summary> /// /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception> /// <exception cref="ArgumentException">destinationFileName is a zero-length string, contains only white space, or contains one or more /// invalid characters as defined by InvalidPathChars. -or- destinationFileName specifies a directory.</exception> /// <exception cref="ArgumentNullException">destinationFileName is null.</exception> /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in destinationFileName is invalid (for example, it is on /// an unmapped drive).</exception> /// <exception cref="IOException">destinationFileName already exists. /// -or- An I/O error has occurred. -or- The entry is currently open for writing. /// -or- The entry has been deleted from the archive.</exception> /// <exception cref="NotSupportedException">destinationFileName is in an invalid format /// -or- The ZipArchive that this entry belongs to was opened in a write-only mode.</exception> /// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read /// -or- The entry has been compressed using a compression method that is not supported.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception> /// /// <param name="destinationFileName">The name of the file that will hold the contents of the entry. /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory.</param> public static void ExtractToFile(this ZipArchiveEntry source, String destinationFileName) { ExtractToFile(source, destinationFileName, false); }
internal Boolean IsStillArchiveStreamOwner(ZipArchiveEntry entry) { return(_archiveStreamOwner == entry); }
private void Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) { Stream extraTempStream = null; try { _backingStream = null; //check stream against mode switch (mode) { case ZipArchiveMode.Create: if (!stream.CanWrite) { throw new ArgumentException(SR.CreateModeCapabilities); } break; case ZipArchiveMode.Read: if (!stream.CanRead) { throw new ArgumentException(SR.ReadModeCapabilities); } if (!stream.CanSeek) { _backingStream = stream; extraTempStream = stream = new MemoryStream(); _backingStream.CopyTo(stream); stream.Seek(0, SeekOrigin.Begin); } break; case ZipArchiveMode.Update: if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek) { throw new ArgumentException(SR.UpdateModeCapabilities); } break; default: //still have to throw this, because stream constructor doesn't do mode argument checks throw new ArgumentOutOfRangeException("mode"); } _mode = mode; _archiveStream = stream; _archiveStreamOwner = null; if (mode == ZipArchiveMode.Create) { _archiveReader = null; } else { _archiveReader = new BinaryReader(stream); } _entries = new List <ZipArchiveEntry>(); _entriesCollection = new ReadOnlyCollection <ZipArchiveEntry>(_entries); _entriesDictionary = new Dictionary <String, ZipArchiveEntry>(); _readEntries = false; _leaveOpen = leaveOpen; _centralDirectoryStart = 0; //invalid until ReadCentralDirectory _isDisposed = false; _numberOfThisDisk = 0; //invalid until ReadCentralDirectory _archiveComment = null; switch (mode) { case ZipArchiveMode.Create: _readEntries = true; break; case ZipArchiveMode.Read: ReadEndOfCentralDirectory(); break; case ZipArchiveMode.Update: default: Debug.Assert(mode == ZipArchiveMode.Update); if (_archiveStream.Length == 0) { _readEntries = true; } else { ReadEndOfCentralDirectory(); EnsureCentralDirectoryRead(); foreach (ZipArchiveEntry entry in _entries) { entry.ThrowIfNotOpenable(false, true); } } break; } } catch { if (extraTempStream != null) { extraTempStream.Dispose(); } throw; } }
/// <summary> /// Reading from an excel template , entering data in it and write back to a file /// </summary> /// <param name="filename"></param> /// <returns></returns> public async Task <StorageFile> WriteToFile(string filename, StorageFile targetfile) { //StorageFile targetfile = null; try { var exceltemplatestream = Assembly.Load(new AssemblyName("ExcelManager")).GetManifestResourceStream(@"ExcelManager.Resources.ExcelTemplateFile.xlsx"); System.IO.Compression.ZipArchive zipArchiveExcelTemplate = new System.IO.Compression.ZipArchive(exceltemplatestream); //Data Builder Code ExcelXmlBuilder excelbuilder = new ExcelXmlBuilder(); XmlDocument xstyleDoc = null; string sheet2string = "", sheet1string; List <Cell> sheetcells = new List <Cell>(ExcelSheet.Cells); var styles = zipArchiveExcelTemplate.Entries.FirstOrDefault(x => x.FullName == "xl/styles.xml"); var styledata = GetByteArrayFromStream(styles.Open()); xstyleDoc = GetStyleXDoc(styledata); sheet1string = excelbuilder.BuildSheetXML(ExcelSheet, ref xstyleDoc); if (ExcelSheet2 != null && ExcelSheet2.Cells != null && ExcelSheet2.Cells.Count > 0) { sheet2string = excelbuilder.BuildSheetXML(ExcelSheet2, ref xstyleDoc, ExcelSheet.Cells.Count); sheetcells.AddRange(ExcelSheet2.Cells); } using (var zipStream = await targetfile.OpenStreamForWriteAsync()) { using (System.IO.Compression.ZipArchive newzip = new System.IO.Compression.ZipArchive(zipStream, ZipArchiveMode.Create)) { foreach (var file in zipArchiveExcelTemplate.Entries) { System.IO.Compression.ZipArchiveEntry entry = newzip.CreateEntry(file.FullName); using (Stream ZipFile = entry.Open()) { byte[] data = null; if (file.FullName == "xl/sharedStrings.xml") { data = Encoding.UTF8.GetBytes(excelbuilder.BuildSharedXML(sheetcells)); ZipFile.Write(data, 0, data.Length); } else if (file.FullName == "xl/worksheets/sheet1.xml") { data = Encoding.UTF8.GetBytes(sheet1string); ZipFile.Write(data, 0, data.Length); } else if (file.FullName == "xl/worksheets/sheet2.xml" && sheet2string != "") { data = Encoding.UTF8.GetBytes(sheet2string); ZipFile.Write(data, 0, data.Length); } else if (file.FullName == "xl/styles.xml") { if (xstyleDoc != null) { data = Encoding.UTF8.GetBytes(xstyleDoc.GetXml().Replace("xmlns=\"\"", "")); ZipFile.Write(data, 0, data.Length); } } else { data = GetByteArrayFromStream(file.Open()); ZipFile.Write(data, 0, data.Length); } } } } } } catch { throw; } return(targetfile); }
public ZipFileInfo(System.IO.Compression.ZipArchiveEntry entry, string subpath) { _entry = entry; _subpath = subpath; }
private void CreateZip(ZipArchiveMode mode) { try { if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update) { throw new ArgumentOutOfRangeException("mode"); } // If the mode parameter is set to Read, the stream must support reading. if (mode == ZipArchiveMode.Read && !stream.CanRead) { throw new ArgumentException("Stream must support reading for Read archive mode"); } // If the mode parameter is set to Create, the stream must support writing. if (mode == ZipArchiveMode.Create && !stream.CanWrite) { throw new ArgumentException("Stream must support writing for Create archive mode"); } // If the mode parameter is set to Update, the stream must support reading, writing, and seeking. if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)) { throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode"); } // If the stream is not seekable, then buffer it into memory (same behavior as .NET). if (mode == ZipArchiveMode.Read && !stream.CanSeek) { var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); if (!leaveStreamOpen) { stream.Dispose(); } this.stream = memoryStream; } try { zipFile = mode != ZipArchiveMode.Create && stream.Length != 0 ? SharpCompress.Archive.Zip.ZipArchive.Open(stream) : SharpCompress.Archive.Zip.ZipArchive.Create(); } catch (Exception e) { throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e); } entries = new List <ZipArchiveEntry>(); if (Mode != ZipArchiveMode.Create) { foreach (var entry in zipFile.Entries) { var zipEntry = new ZipArchiveEntry(this, entry); entries.Add(zipEntry); } } } catch { if (!leaveStreamOpen) { stream.Dispose(); } throw; } }
internal void RemoveEntryInternal(ZipArchiveEntry entry) { zipFile.RemoveEntry(entry.entry); entries.Remove(entry); }
internal static void ExtractRelativeToDirectory(this ZipArchiveEntry source, string destinationDirectoryName) => ExtractRelativeToDirectory(source, destinationDirectoryName, overwrite: false);
internal void ReleaseArchiveStream(ZipArchiveEntry entry) { Debug.Assert(_archiveStreamOwner == entry); _archiveStreamOwner = null; }
internal void RemoveEntry(ZipArchiveEntry entry) { _entries.Remove(entry); _entriesDictionary.Remove(entry.FullName); }
public ZipArchiveEntry(Compression.ZipArchiveEntry entry) { _entry = entry; }
private Core.FileStorage.CompressionStorageStrategy NormalizeCompressionStrategy(System.IO.Compression.ZipArchiveEntry entry) => GetCompressionStrategy(System.IO.Path.GetExtension(entry.FullName));
internal void DebugAssertIsStillArchiveStreamOwner(ZipArchiveEntry entry) => Debug.Assert(_archiveStreamOwner == entry);
internal WrappedStream(Stream baseStream, ZipArchiveEntry entry, Action <ZipArchiveEntry> onClosed) : this(baseStream, false, entry, onClosed) { }
public ZipArchiveEntry(System.IO.Compression.ZipArchiveEntry zipArchiveEntry) { Entry = zipArchiveEntry; }