public GetEntry ( string entryName ) : System.IO.Compression.ZipArchiveEntry | ||
entryName | string | |
Résultat | System.IO.Compression.ZipArchiveEntry |
public string ReadArchive(Stream archiveStream, string path) { using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read)) { var zipArchiveEntry = archive.GetEntry(path); using (var stream = zipArchiveEntry.Open()) using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); return content; } } }
public static List<ReplayKeyPoint> LoadReplay(string fileName) { var path = Path.Combine(Config.Instance.ReplayDir, fileName); if(!File.Exists(path)) return new List<ReplayKeyPoint>(); const string jsonFile = "replay.json"; string json; using(var fs = new FileStream(path, FileMode.Open)) using(var archive = new ZipArchive(fs, ZipArchiveMode.Read)) using(var sr = new StreamReader(archive.GetEntry(jsonFile).Open())) json = sr.ReadToEnd(); return (List<ReplayKeyPoint>)JsonConvert.DeserializeObject(json, typeof(List<ReplayKeyPoint>)); }
/// <summary> /// Downloads and interprets the ZIP file CTS uploads for Google. This is primarily to get route colors and route schedules. /// </summary> private static GoogleTransitData DoTask() { List<GoogleRoute> routes = null; List<GoogleRouteSchedule> schedules = null; using (var archive = new ZipArchive(GetZipFile())) { var routesEntry = archive.GetEntry("routes.txt"); if (routesEntry == null) { throw new FileNotFoundException("The Google Transit archive did not contain routes.txt."); } var scheduleEntry = archive.GetEntry("stop_times.txt"); if (scheduleEntry == null) { throw new FileNotFoundException("The Google Transit archive did not contain stop_times.txt."); } routes = ParseRouteCSV(routesEntry); schedules = ParseScheduleCSV(scheduleEntry); } return new GoogleTransitData { Routes = routes, Schedules = schedules }; }
/// <summary> /// Downloads and interprets the ZIP file CTS uploads for Google. This is primarily to get route colors and route schedules. /// </summary> private static async Task<Tuple<List<GoogleRoute>, List<GoogleRouteSchedule>>> DoTask() { List<GoogleRoute> routes = null; List<GoogleRouteSchedule> schedules = null; var stream = await GetZipFileAsync(); using (var archive = new ZipArchive(stream)) { var routesEntry = archive.GetEntry("routes.txt"); if (routesEntry == null) { throw new FileNotFoundException("The Google Transit archive did not contain routes.txt."); } var scheduleEntry = archive.GetEntry("stop_times.txt"); if (scheduleEntry == null) { throw new FileNotFoundException("The Google Transit archive did not contain stop_times.txt."); } routes = ParseRouteCSV(routesEntry); schedules = ParseScheduleCSV(scheduleEntry); } return Tuple.Create(routes, schedules); }
public void ReduceXap_CreateNewFile_Test() { var fileSystem = Substitute.For<IFileSystem>(); var console = new StringWriter(); CreateFakeInputXap(fileSystem, ZipArchiveMode.Read, "A", "B"). AddResourceAssemblyPart("en", "A"). AddResourceAssemblyPart("en-US", "A"). AddResourceAssemblyPart("en", "B"); CreateFakeSourceXap(fileSystem, "A", "C"); MemoryStream outputStream = new MemoryStream(); fileSystem.FileExists("Output.xap").Returns(true); fileSystem.OpenArchive("Output.xap", ZipArchiveMode.Create).Returns(new ZipArchive(outputStream, ZipArchiveMode.Create, true)); var options = new Options() { Input = "Input.xap", Sources = new[] { "Source.xap" }, Output = "Output.xap" }; var builder = new XapBuilder(); builder.AddAssemblyPart("A", 1000); var minifier = new XapMinifier(fileSystem, console); minifier.ReduceXap(options); var output = new ZipArchive(outputStream, ZipArchiveMode.Read, true); Assert.AreEqual(3, output.Entries.Count); Assert.IsNotNull(output.GetEntry("B.dll")); Assert.IsNotNull(output.GetEntry("en\\B.resources.dll")); }
/// <summary> /// Creates an archive entry or throw an <see cref="InvalidOperationException"/> if already exists. /// </summary> private ZipArchiveEntry CreateEntryIfNotExists(string entryName) { if (_archive.GetEntry(entryName) != null) { throw new InvalidOperationException(string.Format(Resources.Resources.zip_entry_exists, entryName)); } return(_archive.CreateEntry(entryName)); }
public void ZipGetEntryReadMode() { File.Copy("archive.zip", "test.zip", overwrite: true); using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open), ZipArchiveMode.Read)) { var entry = archive.GetEntry("foo.txt"); Assert.IsNotNull(entry); var nullEntry = archive.GetEntry("nonexisting"); Assert.IsNull(nullEntry); } }
/// <summary> /// Run a vocabulary test against two data files inside a zip file </summary> public static void AssertVocabulary(Analyzer a, Stream zipFile, string voc, string @out) { using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Read, false, Encoding.UTF8)) { using (Stream v = zip.GetEntry(voc).Open()) { using (Stream o = zip.GetEntry(@out).Open()) { AssertVocabulary(a, v, o); } } } }
//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); }
public void Restore(string slnFile) { using (var resourceStream = _fileSystem.OpenResource("slnRun.Resources.nuget.zip")) using (var zipFile = new ZipArchive(resourceStream)) using (var nugetInputFile = zipFile.GetEntry("nuget.exe").Open()) { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); _fileSystem.CreateDirectory(tempPath); try { var targetPath = Path.Combine(tempPath, "nuget.exe"); using (var nugetOutputFile = _fileSystem.CreateFile(targetPath)) nugetInputFile.CopyTo(nugetOutputFile); var sb = new StringBuilder(); var exitCode = _processRunner.Run(targetPath, $"restore \"{slnFile}\"", x => { sb.Append(x); }); if (exitCode != 0) { _logger.Error(sb.ToString()); throw new SlnRunException("nuget package restore failed."); } } finally { _fileSystem.DeleteDirectory(tempPath); } } }
public void Load(ZipArchive iArchive) { JObject pJOtImages = null; ZipArchiveEntry pZAEImages = iArchive.GetEntry("images.json"); if (pZAEImages != null) { using (Stream pStmImages = pZAEImages.Open()) { using (StreamReader pSRrReader = new StreamReader(pStmImages, Encoding.UTF8, false, 1024, true)) { using (JsonTextReader pJTRReader = new JsonTextReader(pSRrReader)) { pJOtImages = JObject.Load(pJTRReader); } } } } JArray pJAyImages = pJOtImages["images"].Value<JArray>(); ; foreach(JObject curImage in pJAyImages) { ProjectImage pPIeImage = ProjectImage.FromJSON(curImage); ZipArchiveEntry pZAEImage = iArchive.GetEntry(pPIeImage.ID); if (pZAEImage != null) { using (Stream pStmImage = pZAEImage.Open()) { pPIeImage.Image = Image.FromStream(pStmImage); cDicImages.Add(pPIeImage.ID, pPIeImage); } } } }
private async void BlankPage11_Loaded(object sender, RoutedEventArgs e) { var f = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/giftest.gif")); f = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/vedio.mp4")); f = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/live.jpg")); MemoryStream ms = null; using (var s = await f.OpenReadAsync()) { using (var zip = new ZipArchive(s.AsStream(), ZipArchiveMode.Read)) { ZipArchiveEntry entry = zip.GetEntry("formats/living/living.mp4"); if (entry != null) { using (var st = entry.Open()) { ms = new MemoryStream(); st.CopyTo(ms); ms.Flush(); } } } } var m = ms.AsRandomAccessStream(); m.Seek(0); MediaElement1.SetSource(m, "video/mp4"); MediaElement1.Play(); }
public async static Task DownloadAndExtract( string uri, params Tuple<string, string>[] files) { var tmpFile = Path.GetTempPath() + "pomelo_" + Guid.NewGuid().ToString() + ".zip"; Console.WriteLine("Downloading from " + uri); using (var webClient = new HttpClient() { Timeout = new TimeSpan(1, 0, 0), MaxResponseContentBufferSize = 1024 * 1024 * 50 }) { var bytes = await webClient.GetByteArrayAsync(uri); File.WriteAllBytes(tmpFile, bytes); Console.WriteLine("Downloaded"); } using (var fileStream = new FileStream(tmpFile, FileMode.Open)) using (var archive = new ZipArchive(fileStream)) { foreach (var file in files) { var entry = archive.GetEntry(file.Item1); if (entry == null) throw new Exception("Could not find file '" + file.Item1 + "'."); Directory.CreateDirectory(Path.GetDirectoryName(file.Item2)); using (var entryStream = entry.Open()) using (var dllStream = File.OpenWrite(file.Item2)) { entryStream.CopyTo(dllStream); } } } File.Delete(tmpFile); }
public override IRegressionProblemData LoadData(IDataDescriptor id) { var descriptor = (ResourceRegressionDataDescriptor)id; var instanceArchiveName = GetResourceName(FileName + @"\.zip"); using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) { var entry = instancesZipFile.GetEntry(descriptor.ResourceName); NumberFormatInfo numberFormat; DateTimeFormatInfo dateFormat; char separator; using (Stream stream = entry.Open()) { TableFileParser.DetermineFileFormat(stream, out numberFormat, out dateFormat, out separator); } TableFileParser csvFileParser = new TableFileParser(); using (Stream stream = entry.Open()) { csvFileParser.Parse(stream, numberFormat, dateFormat, separator, true); } Dataset dataset = new Dataset(csvFileParser.VariableNames, csvFileParser.Values); if (!descriptor.CheckVariableNames(csvFileParser.VariableNames)) { throw new ArgumentException("Parsed file contains variables which are not in the descriptor."); } return descriptor.GenerateRegressionData(dataset); } }
public static async System.Threading.Tasks.Task<string> GetRootFilePathAsync(ZipArchive epubArchive) { //Checking if file exist const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml"; ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH); string full_path = string.Empty; if (containerFileEntry == null) throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH)); //Loading container.xml to memmory... using (Stream containerStream = containerFileEntry.Open()) { // ...and trying to parse it in order to get the full path to the .opf file, like full-path="SomeFolder/SomeFileWithContent.opf" full_path = await XmlUtils.GetFilePathAttributeAsync(containerStream); } //Checking if the problem exist... if (full_path == "full-path attribute not found" || full_path == "Yes, rootfile not found...") { Debug.WriteLine(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path)); throw new Exception(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path)); } return full_path; //Initial code sucks and is not compatible with Win 8.1 runtime framework /* xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container"); XmlNode rootFileNode = containerDocument.DocumentElement.SelectSingleNode("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager); return rootFileNode.Attributes["full-path"].Value; */ }
private static void AssertZipEntry(ZipArchive archive, string fileName, string content) { ZipArchiveEntry entry = archive.GetEntry(fileName); Assert.NotNull(entry); using (var streamReader = new StreamReader(entry.Open())) { Assert.Equal(content, streamReader.ReadLine()); } }
public void ZipCreateFromDirectory() { if (File.Exists ("foo.zip")) File.Delete ("foo.zip"); ZipFile.CreateFromDirectory ("foo", "foo.zip"); Assert.IsTrue(File.Exists("foo.zip")); using (var archive = new ZipArchive (File.Open ("foo.zip", FileMode.Open), ZipArchiveMode.Read)) { Assert.IsNotNull (archive.GetEntry ("foo.txt")); Assert.IsNotNull (archive.GetEntry ("bar.txt")); Assert.IsNotNull (archive.GetEntry ("foobar/foo.txt")); Assert.IsNotNull (archive.GetEntry ("foobar/bar.txt")); } }
public CryptRWArchive(string filePath, string encryptionKey) { EncryptionKey = encryptionKey; _arc = ZipFile.Open(filePath, ZipArchiveMode.Update); //open R/W if (_arc.GetEntry("crypt.index")!=null) { LoadIndex(); } }
public void ZipCreateFromDirectoryIncludeBase() { if (File.Exists ("foo.zip")) File.Delete ("foo.zip"); ZipFile.CreateFromDirectory ("foo", "foo.zip", CompressionLevel.Fastest, includeBaseDirectory: true); Assert.IsTrue (File.Exists ("foo.zip")); using (var archive = new ZipArchive (File.Open ("foo.zip", FileMode.Open), ZipArchiveMode.Read)) { Assert.IsNotNull (archive.GetEntry ("foo/foo.txt")); Assert.IsNotNull (archive.GetEntry ("foo/bar.txt")); Assert.IsNotNull (archive.GetEntry ("foo/foobar/foo.txt")); Assert.IsNotNull (archive.GetEntry ("foo/foobar/bar.txt")); } }
public static EpubNavigation ReadNavigation(ZipArchive epubArchive, string contentDirectoryPath, EpubPackage package) { EpubNavigation result = new EpubNavigation(); string tocId = package.Spine.Toc; if (String.IsNullOrEmpty(tocId)) throw new Exception("EPUB parsing error: TOC ID is empty."); EpubManifestItem tocManifestItem = package.Manifest.FirstOrDefault(item => String.Compare(item.Id, tocId, StringComparison.OrdinalIgnoreCase) == 0); if (tocManifestItem == null) throw new Exception(String.Format("EPUB parsing error: TOC item {0} not found in EPUB manifest.", tocId)); string tocFileEntryPath = ZipPathUtils.Combine(contentDirectoryPath, tocManifestItem.Href); ZipArchiveEntry tocFileEntry = epubArchive.GetEntry(tocFileEntryPath); if (tocFileEntry == null) throw new Exception(String.Format("EPUB parsing error: TOC file {0} not found in archive.", tocFileEntryPath)); if (tocFileEntry.Length > Int32.MaxValue) throw new Exception(String.Format("EPUB parsing error: TOC file {0} is bigger than 2 Gb.", tocFileEntryPath)); XmlDocument containerDocument; using (Stream containerStream = tocFileEntry.Open()) containerDocument = XmlUtils.LoadDocument(containerStream); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(containerDocument.NameTable); xmlNamespaceManager.AddNamespace("ncx", "http://www.daisy.org/z3986/2005/ncx/"); XmlNode headNode = containerDocument.DocumentElement.SelectSingleNode("ncx:head", xmlNamespaceManager); if (headNode == null) throw new Exception("EPUB parsing error: TOC file does not contain head element"); EpubNavigationHead navigationHead = ReadNavigationHead(headNode); result.Head = navigationHead; XmlNode docTitleNode = containerDocument.DocumentElement.SelectSingleNode("ncx:docTitle", xmlNamespaceManager); if (docTitleNode == null) throw new Exception("EPUB parsing error: TOC file does not contain docTitle element"); EpubNavigationDocTitle navigationDocTitle = ReadNavigationDocTitle(docTitleNode); result.DocTitle = navigationDocTitle; result.DocAuthors = new List<EpubNavigationDocAuthor>(); foreach (XmlNode docAuthorNode in containerDocument.DocumentElement.SelectNodes("ncx:docAuthor", xmlNamespaceManager)) { EpubNavigationDocAuthor navigationDocAuthor = ReadNavigationDocAuthor(docAuthorNode); result.DocAuthors.Add(navigationDocAuthor); } XmlNode navMapNode = containerDocument.DocumentElement.SelectSingleNode("ncx:navMap", xmlNamespaceManager); if (navMapNode == null) throw new Exception("EPUB parsing error: TOC file does not contain navMap element"); EpubNavigationMap navMap = ReadNavigationMap(navMapNode); result.NavMap = navMap; XmlNode pageListNode = containerDocument.DocumentElement.SelectSingleNode("ncx:pageList", xmlNamespaceManager); if (pageListNode != null) { EpubNavigationPageList pageList = ReadNavigationPageList(pageListNode); result.PageList = pageList; } result.NavLists = new List<EpubNavigationList>(); foreach (XmlNode navigationListNode in containerDocument.DocumentElement.SelectNodes("ncx:navList", xmlNamespaceManager)) { EpubNavigationList navigationList = ReadNavigationList(navigationListNode); result.NavLists.Add(navigationList); } return result; }
//Parsing metadata, manifest, spine and guide public static async Task<EpubPackage> ReadPackageAsync(ZipArchive epubArchive, string rootFilePath) { EpubPackage result = new EpubPackage(); XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { // XmlResolver = null, Async = true, DtdProcessing = DtdProcessing.Ignore }; ZipArchiveEntry rootFileEntry = epubArchive.GetEntry(rootFilePath); if (rootFileEntry == null) throw new Exception(string.Format("EPUB parsing error: {0} file not found in archive.", rootFilePath)); //Starting content.opf parsing... using (Stream containerStream = rootFileEntry.Open()) { using (XmlReader xmlReader = XmlReader.Create(containerStream, xmlReaderSettings)) { await xmlReader.ReadToFollowingAsync("package", "http://www.idpf.org/2007/opf"); //Trying to get version attribute from <package version=... //Looks like we only need EPUB version data and we don`t care about unique-identifier //if EPUB version is FUBAR then throwing an exeption xmlReader.MoveToAttribute("version"); string epubVersionValue = xmlReader.Value; if (epubVersionValue == "2.0") result.EpubVersion = EpubVersion.EPUB_2; else if (epubVersionValue == "3.0") result.EpubVersion = EpubVersion.EPUB_3; else throw new Exception(String.Format("Unsupported EPUB version: {0}.", epubVersionValue)); //Reading metadata EpubMetadata metadata = await ReadMetadataAsync(xmlReader, result.EpubVersion); result.Metadata = metadata; //Reading manifest EpubManifest manifest = await ReadManifestAsync(xmlReader); result.Manifest = manifest; //Reading spine EpubSpine spine = await ReadSpineAsync(xmlReader); result.Spine = spine; //Reading guide. And we actually don`t care if it is no present in our EPUB... bool isGuidePresent = await xmlReader.ReadToFollowingAsync("guide", "http://www.idpf.org/2007/opf"); if (isGuidePresent) { EpubGuide guide = await ReadGuideAsync(xmlReader); result.Guide = guide; } } } return result; }
public void Load(ZipArchive iArchive) { ZipArchiveEntry pZAELogo = iArchive.GetEntry("logo.jpg"); if(pZAELogo != null) { using (Stream pStmLogo = pZAELogo.Open()) { CompanyLogo = Image.FromStream(pStmLogo); } } ZipArchiveEntry pZAEBackground = iArchive.GetEntry("background.jpg"); if (pZAEBackground != null) { using (Stream pStmBackgroundImage = pZAEBackground.Open()) { BackgroundImage = Image.FromStream(pStmBackgroundImage); } } }
/// <summary> /// Gets raw data from the data provider. /// </summary> /// <returns>The data as a big string.</returns> /// <param name="countryIsoA2">ISO A2 of the country to get regions for.</param> public async Task<string> GetSourceData(string countryIsoA2) { var countryImportUrl = new Uri(this.importURL.ToString().Replace("$$", countryIsoA2)); var webClient = this.webClientFactory.Create(); var rawResponse = await webClient.DownloadDataTaskAsync(countryImportUrl); var zipArchive = new ZipArchive(new MemoryStream(rawResponse), ZipArchiveMode.Read); var dataEntry = zipArchive.GetEntry(countryIsoA2 + ".txt"); var responseData = await new StreamReader(dataEntry.Open()).ReadToEndAsync(); return responseData; }
/// <summary> /// Reads lines from a specific stream. /// </summary> /// <param name="zip">The zip file.</param> /// <param name="entryName">A path, relative to the root of the archive, that identifies the entry to retrieve.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="removeEmptyLine">true if need remove the empty line; otherwise, false.</param> /// <returns>Lines from the specific stream reader.</returns> /// <exception cref="ArgumentNullException">file was null.</exception> /// <exception cref="FileNotFoundException">file was not found.</exception> /// <exception cref="DirectoryNotFoundException">The directory of the file was not found.</exception> /// <exception cref="NotSupportedException">Cannot read the file.</exception> /// <exception cref="IOException">An I/O error occurs.</exception> /// <exception cref="ObjectDisposedException">The zip archive has been disposed.</exception> /// <exception cref="NotSupportedException">The zip archive does not support reading.</exception> /// <exception cref="InvalidDataException">The zip archive is corrupt, and the entry cannot be retrieved.</exception> public static IEnumerable <string> ReadLines(System.IO.Compression.ZipArchive zip, string entryName, Encoding encoding, bool removeEmptyLine = false) { var entry = zip?.GetEntry(entryName); if (entry == null) { throw new FileNotFoundException("file is not found."); } using var stream = entry.Open(); return(ReadLines(stream, encoding, removeEmptyLine)); }
private static void LoadFiles(ZipArchive archive, Feed feed, KeyValuePair<string, Type> map) { ZipArchiveEntry entry = archive.GetEntry(map.Key); using (Stream stream = entry.Open()) { using (TextReader tr = new StreamReader(stream)) { LoadCsvFile(feed, map, tr); } } }
public void AddOrUpdateItem(string name, byte[] data) { name = name ?? throw new ArgumentNullException(nameof(name)); ZipArchiveEntry entry; if (!ItemExists(name)) { entry = _archive.CreateEntry(name); } else { entry = _archive.GetEntry(name); } using (Stream wr = entry.Open()) { wr.Write(data, 0, data.Length); } }
public static void FixupAarClass(string filename, string artName) { using (var fileStream = new FileStream(filename, FileMode.Open)) using (var zipArchive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update, true)) { var entryNames = zipArchive.Entries.Select(zae => zae.FullName).ToList(); Console.WriteLine("Found {0} entries in {1}", entryNames.Count, filename); foreach (var entryName in entryNames) { var newName = entryName; // Open the old entry var oldEntry = zipArchive.GetEntry(entryName); // We are only re-adding non empty folders, otherwise we end up with a corrupt zip in mono if (!string.IsNullOrEmpty(oldEntry.Name)) { // UGLY WORKAROUND // In the some of the native libraries, there exist multiple .aar files which have a libs/r-classes.jar file. // In Xamarin.Android, there is a Task "CheckDuplicateJavaLibraries" which inspects jar files being pulled in from .aar files // in assemblies to see if there exist any files with the same name but different content, and will throw an error if it finds any. // However, for us, it is perfectly valid to have this scenario and we should not see an error. var newFile = Path.GetFileName(newName); var newDir = Path.GetDirectoryName(newName); if (newFile.StartsWith("r", StringComparison.InvariantCulture)) { newName = newDir + "/" + "r-" + artName + ".jar"; } Console.WriteLine("Renaming: {0} to {1}", entryName, newName); // Create a new entry based on our new name var newEntry = zipArchive.CreateEntry(newName); // Copy file contents over if they exist if (oldEntry.Length > 0) { using (var oldStream = oldEntry.Open()) using (var newStream = newEntry.Open()) { oldStream.CopyTo(newStream); } } } // Delete the old entry regardless of if it's a folder or not oldEntry.Delete(); } } }
/// <summary> /// Loads an image from a zip archive /// </summary> /// <param name="archive">The archive to load from</param> /// <returns>The loaded image</returns> public Image LoadImage(ZipArchive archive) { Image image = null; // Open file in archive ZipArchiveEntry imageEntry = archive.GetEntry(StringResources.PATH_IMAGE_DIR + Path); using (Stream stream = imageEntry.Open()) { // Load the image image = Image.FromStream(stream); } return image; }
public string reWriteRecord(string entryName, byte[] data) { if (string.IsNullOrWhiteSpace(entryName)) { entryName = Guid.NewGuid().ToString(); } ZipArchiveEntry newEntry; if (null != (newEntry = linkedArchive.GetEntry(entryName))) { newEntry.Delete(); //throw new Exception(string.Format("entry {0} already exists in archive", entryName)); } newEntry = linkedArchive.CreateEntry(entryName, CompressionLevel.Fastest); Stream es = newEntry.Open(); es.Write(data, 0, data.Length); es.Close(); return(entryName); }
public static string GetRootFilePath(ZipArchive epubArchive) { const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml"; ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH); if (containerFileEntry == null) throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH)); XmlDocument containerDocument; using (Stream containerStream = containerFileEntry.Open()) containerDocument = XmlUtils.LoadDocument(containerStream); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(containerDocument.NameTable); xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container"); XmlNode rootFileNode = containerDocument.DocumentElement.SelectSingleNode("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager); return rootFileNode.Attributes["full-path"].Value; }
public static void FixupAarResource(string filename, string artName) { using (var fileStream = new FileStream(filename, FileMode.Open)) using (var zipArchive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update, true)) { var entryNames = zipArchive.Entries.Select(zae => zae.FullName).ToList(); Console.WriteLine("Found {0} entries in {1}", entryNames.Count, filename); foreach (var entryName in entryNames) { var newName = entryName; // Open the old entry var oldEntry = zipArchive.GetEntry(entryName); // We are only re-adding non empty folders, otherwise we end up with a corrupt zip in mono if (!string.IsNullOrEmpty(oldEntry.Name)) { var newFile = Path.GetFileName(newName); var newDir = Path.GetDirectoryName(newName); //Fix R.text in different .aar if (newFile.Contains("R.txt")) { newName = newDir + "/" + "R-" + artName + ".txt"; } Console.WriteLine("Renaming: {0} to {1}", entryName, newName); // Create a new entry based on our new name var newEntry = zipArchive.CreateEntry(newName); // Copy file contents over if they exist if (oldEntry.Length > 0) { using (var oldStream = oldEntry.Open()) using (var newStream = newEntry.Open()) { oldStream.CopyTo(newStream); } } } // Delete the old entry regardless of if it's a folder or not oldEntry.Delete(); } } }
public void ZipGetEntryCreateMode() { File.Copy("archive.zip", "test.zip", overwrite: true); using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open), ZipArchiveMode.Create)) { try { archive.GetEntry("foo"); } catch(NotSupportedException ex) { return; } Assert.Fail(); } }
public static bool UnInstall(List<Parameter> parms) { FileStream fs = new FileStream(GetParameter("Name", parms) + ".NAVY", FileMode.Open); ZipArchive za = new ZipArchive(fs, ZipArchiveMode.Read); FileStream fs2 = new FileStream(GetParameter("Name", parms) + ".NAVY.Backup", FileMode.Open); ZipArchive zbackup = new ZipArchive(fs2, ZipArchiveMode.Read); ZipArchiveEntry manifest = za.GetEntry("manifest.xml"); Package p = PackageFile.Load(manifest.Open()); Console.WriteLine("Uninstalling {0} ...", p.App.Name); try { Directory.Delete("ORIGINAL", true); } catch { }; Directory.CreateDirectory("ORIGINAL"); using (PowerShell psi = PowerShell.Create()) { psi.AddScript("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned"); psi.AddScript(NAVTools); foreach (var delta in p.Payload.Deltas) { string FileName = delta.DeltaFile.Split('.')[0]; // Extract the original from the ZIP backup ZipArchiveEntry zip = zbackup.GetEntry(FileName + ".TXT"); zip.ExtractToFile("ORIGINAL\\" + FileName + ".TXT"); Console.WriteLine(" - object {0} {1}", delta.Type, delta.ID); psi.AddScript(@"Import-NAVApplicationObject -Confirm:$false ORIGINAL\\" + FileName + ".TXT -DatabaseName " + GetParameter("DatabaseName", parms)); ExecutePowerShell(psi, 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); } return true; }
public TheTvDbUpdateContainer Parse(Windows.Storage.Streams.IInputStream updateContainerStream, TheTvDbInterval interval) #endif { if (updateContainerStream == null) throw new ArgumentNullException(nameof(updateContainerStream)); #if WINDOWS_PORTABLE || WINDOWS_DESKTOP using (var archive = new ZipArchive(updateContainerStream, ZipArchiveMode.Read)) #elif WINDOWS_UAP using (var archive = new ZipArchive(updateContainerStream.AsStreamForRead(), ZipArchiveMode.Read)) #endif { var entryName = $"updates_{interval.ToApiString()}.xml"; var updateContainerRaw = archive.GetEntry(entryName).ReadToEnd(); return ParseUncompressed(updateContainerRaw); } }
private static XElement GetXml(InternalZipFileInfo packageFileInfo, IMSBuildNuGetProjectSystem msBuildNuGetProjectSystem) { string content; using (var packageStream = File.OpenRead(packageFileInfo.ZipArchivePath)) { var zipArchive = new ZipArchive(packageStream); var zipArchivePackageEntry = zipArchive.GetEntry(packageFileInfo.ZipArchiveEntryFullName); if(zipArchivePackageEntry == null) { throw new ArgumentException("internalZipFileInfo"); } content = Preprocessor.Process(zipArchivePackageEntry, msBuildNuGetProjectSystem); } return XElement.Parse(content, LoadOptions.PreserveWhitespace); }
public Stream Export(List<TeamResult> results, Stream excelTemplate) { using (var z = new ZipArchive(excelTemplate, ZipArchiveMode.Update)) { ZipArchiveEntry sharedString = z.GetEntry("xl/sharedStrings.xml"); byte[] data; using (Stream stream = sharedString.Open()) { data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); } string content = Encoding.UTF8.GetString(data, 0, data.Length); string teamNameFormat = "[$teamName{0}]"; string teamScoreFormat = "[$teamScore{0}]"; for (int i = 0; i < results.Count; ++i) { content = content.Replace(string.Format(teamNameFormat, (i + 1)), results[i].Name); content = content.Replace(string.Format(teamScoreFormat, (i + 1)), Math.Round(results[i].Score, 2).ToString()); } for (int i = results.Count; i < 200; ++i) { string teamName = string.Format(teamNameFormat, (i + 1)); if (!content.Contains(teamName)) { break; } content = content.Replace(teamName, string.Empty); content = content.Replace(string.Format(teamScoreFormat, (i + 1)), string.Empty); } sharedString.Delete(); sharedString = z.CreateEntry("xl/sharedStrings.xml"); using (StreamWriter stream = new StreamWriter(sharedString.Open())) { stream.Write(content); } } return excelTemplate; }
/// <summary> /// このアプリケーションを適用可能な最新版に更新します。 /// </summary> /// <returns>更新の完了を通知するタスク。</returns> public override async Task UpdateAsync() { // Candy.Updater.exe だけは Candy.exe 側で書き換える var client = new HttpClient(); var updateServiceUrl = GetUpdateServiceUrl(); var json = await client.GetStringAsync(updateServiceUrl).ConfigureAwait(false); var latest = JsonConvert.DeserializeObject<UpdateSummary>(json); using (var stream = await client.GetStreamAsync(latest.PackagePath).ConfigureAwait(false)) using (var archive = new ZipArchive(stream, ZipArchiveMode.Read)) { var entry = archive.GetEntry("Candy.Updater.exe"); if (entry != null) { using (var updater = entry.Open()) using (var dest = File.OpenWrite("Candy.Updater.exe")) { dest.SetLength(0); await updater.CopyToAsync(dest).ConfigureAwait(false); } } } var arguments = String.Format(@"-n ""{0}"" -p ""{1}"" -u ""{2}"" -s", DisplayName.Replace("\"", "\\\""), InstalledPath, updateServiceUrl); var process = new Process { StartInfo = new ProcessStartInfo { FileName = "Candy.Updater.exe", Arguments = arguments, }, }; process.Start(); // 自身を終了させる(Candy.Updater.exe は Candy.exe が終了するまで待機してくれる) Application.Current.Shutdown(); // 完了しないタスクで呼出元をアプリケーション終了まで待機させ続ける await _never.ConfigureAwait(false); }
private void AddFileToSharePoint(Folder rootFolder, string filePath, Stream fileStream) { NuGetLogUtils.Verbose(string.Format("Saved file [{0}] to SharePoint", filePath)); MemoryStream clonedNuPkgStream = null; MemoryStream clonedZipNuPkgStream = null; try { if (filePath.ToLower().EndsWith(".nupkg")) { clonedNuPkgStream = new MemoryStream(); clonedZipNuPkgStream = new MemoryStream(); CopyStream(fileStream, clonedNuPkgStream); fileStream.Position = 0; CopyStream(fileStream, clonedZipNuPkgStream); fileStream.Position = 0; clonedNuPkgStream.Position = 0; clonedZipNuPkgStream.Position = 0; } else { return; } var context = rootFolder.Context; var fileName = Path.GetFileName(filePath); var fileFolderPath = Path.GetDirectoryName(filePath); InvalidatePathToFilesCache(fileFolderPath); var fileFolder = EnsureFolder(context, rootFolder, fileFolderPath); var file = fileFolder.Files.Add(new FileCreationInformation { ContentStream = fileStream, Overwrite = true, Url = fileName }); context.ExecuteQuery(); if (clonedNuPkgStream != null) { NuGetLogUtils.Verbose("Saving .nupkg metadata to SharePoint..."); var zipPackage = new ZipPackage(clonedNuPkgStream); var zipArchive = new System.IO.Compression.ZipArchive(clonedZipNuPkgStream); NuGetLogUtils.Info("Fetching nuspec file..."); var manifestFileName = string.Format("{0}.nuspec", zipPackage.Id); var manifestFile = zipArchive.GetEntry(manifestFileName); var nuspecXmlValue = string.Empty; using (var stramReader = new StreamReader(manifestFile.Open())) { nuspecXmlValue = stramReader.ReadToEnd(); } NuGetLogUtils.Verbose("Updating nuspec and version values..."); if (!string.IsNullOrEmpty(nuspecXmlValue)) { // update properties var fileItem = file.ListItemAllFields; context.Load(fileItem); fileItem.ParseAndSetFieldValue("PackageNuspecXml", nuspecXmlValue); fileItem.ParseAndSetFieldValue("PackageVersion", zipPackage.Version.ToString()); fileItem.ParseAndSetFieldValue("PackageId", zipPackage.Id); fileItem.Update(); context.ExecuteQuery(); } } NuGetLogUtils.Verbose(string.Format("Saved file [{0}] to SharePoint", filePath)); } finally { if (clonedNuPkgStream != null) { clonedNuPkgStream.Dispose(); clonedNuPkgStream = null; } if (clonedZipNuPkgStream != null) { clonedZipNuPkgStream.Dispose(); clonedZipNuPkgStream = null; } } }
public override bool HasEntry(string filename) { return(_zip.GetEntry(filename) != null); }