private static List <XDocument> GetContentTypePackageParts( Package filePackage, string contentType) { // Get all of the package parts contained in the package // and then write the URI and content type of each one to the console. PackagePartCollection packageParts = filePackage.GetParts(); var relevantPackageParts = packageParts .Where(pp => pp.ContentType == contentType) .ToList(); foreach (PackagePart packagePart in relevantPackageParts) { Console.WriteLine("Package part URI: {0}", packagePart.Uri); Console.WriteLine("Content type: {0}", packagePart.ContentType); } var results = relevantPackageParts .Select(pp => GetXDocumentFromPackagePart(pp)) .ToList(); return(results); }
}// end:CopyStream() private static void ExtractPackage(object p) { int errors = 0; using (ZipPackage zip = (ZipPackage)ZipPackage.Open(File.OpenRead("MCForge.zip"))) { PackagePartCollection pc = zip.GetParts(); foreach (ZipPackagePart item in pc) { try { CopyStream(item.GetStream(), File.Create("./" + Uri.UnescapeDataString(item.Uri.ToString()))); } catch { try { Directory.CreateDirectory("./" + item.Uri.ToString().Substring(0, item.Uri.ToString().LastIndexOfAny("\\/".ToCharArray()))); CopyStream(item.GetStream(), File.Create("./" + Uri.UnescapeDataString(item.Uri.ToString()))); } catch (IOException e) { Server.ErrorLog(e); Server.s.Log("Caught ignoreable Error. See log for more details. Will continue with rest of files."); errors++; } } // To make life easier, we reload settings now, to maker it less likely to need restart Command.all.Find("server").Use(null, "reload"); //Reload, as console if (item.Uri.ToString().ToLower().Contains("sql.sql")) // If it's in there, they backed it up, meaning they want it restored { Database.fillDatabase(item.GetStream()); } } } Player.SendMessage((Player)p, "Server restored" + (errors > 0 ? " with errors. May be a partial restore" : "") + ". Restart is reccommended, though not required."); }
public bool Open(string path) { try { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); memStream = new MemoryStream(); memStream.Write(buffer, 0, (int)fs.Length); buffer = null; fs.Close(); package = Package.Open(memStream, FileMode.Open, FileAccess.ReadWrite); docParts = new Dictionary <string, DocumentPart>(); PackagePartCollection parts = package.GetParts(); foreach (PackagePart part in parts) { DocumentPart docPart = new DocumentPart(part); docParts.Add(part.Uri.ToString(), docPart); } filePath = path; dirty = false; return(true); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); return(false); } }
private int extractTheme(FileInfo zipFile) { string themeName = zipFile.Name.Remove(zipFile.Name.Length - zipFile.Extension.Length); string destFolder = Path.Combine(themedir, themeName); try { using (Package zip = Package.Open(zipFile.FullName, FileMode.Open)) { PackagePartCollection parts = zip.GetParts(); if (Directory.Exists(destFolder)) { return(1); } else { Directory.CreateDirectory(destFolder); } foreach (PackagePart part in parts) { /* not sure what's this good for */ /* String archive = part.Uri.ToString().Replace(@"/", @"\"); */ String destFile = destFolder + part.Uri.ToString(); using (FileStream outFileStream = new FileStream(destFile, FileMode.CreateNew, FileAccess.ReadWrite)) { using (Stream inStream = part.GetStream()) { long bufferSize = inStream.Length < BUFFER_SIZE ? inStream.Length : BUFFER_SIZE; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; long bytesWritten = 0; while ((bytesRead = inStream.Read(buffer, 0, buffer.Length)) != 0) { outFileStream.Write(buffer, 0, bytesRead); bytesWritten += bufferSize; } } } } } } catch (System.IO.FileFormatException) { return(2); } if (IsDirectoryEmpty(destFolder)) { Directory.Delete(destFolder); return(2); } else { return(0); } }
public void EnumeratePartsBreak() { FakePackage package = new FakePackage(FileAccess.ReadWrite, false); package.CreatePart(uris [0], "a/a"); package.CreatePart(uris [1], "a/a"); package.CreatePart(uris [2], "a/a"); Assert.IsTrue(package.GetParts() == package.GetParts(), "#1"); try { foreach (PackagePart part in package.GetParts()) { package.DeletePart(part.Uri); } Assert.Fail("This should throw an exception"); } catch { } PackagePartCollection c = package.GetParts(); package.CreatePart(new Uri("/dfds", UriKind.Relative), "a/a"); int count = 0; foreach (PackagePart p in c) { count++; } Assert.AreEqual(3, count, "Three added, one deleted, one added"); }
public static List <IWfProcessDescriptor> ImportProcessDescriptors(Stream stream, Action <string> notifyEveryStep = null) { stream.NullCheck("stream"); List <IWfProcessDescriptor> result = null; using (Package package = ZipPackage.Open(stream)) { notifyEveryStep.Notify("开始导入文件...\n"); PackagePartCollection packageParts = package.GetParts(); WfProcessImporterContext context = new WfProcessImporterContext(packageParts); notifyEveryStep.Notify(string.Format(" 共发现{0}个矩阵定义,{1}个流程矩阵数据,{2}个流程模板文件...\n", context.MatrixDefParts.Count, context.MatrixParts.Count, context.ProcessDescParts.Count)); using (TransactionScope scope = TransactionScopeFactory.Create()) { SaveMatrix(context); notifyEveryStep.Notify(" 导入流程矩阵完成...\n"); result = SaveProcessDescriptor(context); notifyEveryStep.Notify(" 导入流程模板完成...\n"); scope.Complete(); } notifyEveryStep.Notify("文件导入完成!"); } return(result); }
public static Stream ExtractStreamFromZip(string zipFilename, string fileToExtract) { if (IsValidFile(zipFilename)) { try { using (ZipPackage _package = (ZipPackage)Package.Open(zipFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { PackagePartCollection _packageParts = _package.GetParts(); foreach (PackagePart _part in _packageParts) { if (_part.Uri.OriginalString == '/' + fileToExtract) { MemoryStream _stream = new MemoryStream(); CopyStream(_part.GetStream(), _stream as Stream); return(_stream); } } } } catch (Exception ex) { Loggy.Logger.ErrorException("Loading stream from metadata.", ex); } } return(null); }
private void ProcessParts(PackagePartCollection parts) { foreach (PackagePart packagePart in parts) { if (!IsPackageLevelRelationshipsPart(packagePart)) { ProcessRelationsips(packagePart, packagePart.GetRelationships()); } if (IsXmlPart(packagePart.ContentType) || _signatureDefinitions.Contains(packagePart)) { ProcessXmlPart(packagePart); } if (packagePart.ContentType.Equals("image/vnd.ms-photo", StringComparison.OrdinalIgnoreCase)) { if (IsJpegXRSupported()) { ConvertHDPhoto(packagePart); } else { Console.WriteLine("HDPhoto/JpegXR image found. Skipping conversion."); } } } }
private XElement getWorksheet(int worksheetID, PackagePartCollection allParts) { var worksheetName = String.Format("/xl/worksheets/sheet{0}.xml", worksheetID); PackagePart worksheetPart = allParts.Where(x => x.Uri.OriginalString == worksheetName).Single(); return(XElement.Load(XmlReader.Create(worksheetPart.GetStream()))); }
static void Main(string[] args) { try { using (Package fPackage = OpenPackage("*.vsdx", System.Environment.SpecialFolder.Desktop)) { PackagePartCollection fParts = fPackage.GetParts(); foreach (PackagePart fPart in fParts) { Console.WriteLine("Package part: {0}", fPart.Uri); Console.WriteLine("Content type: {0}", fPart.ContentType.ToString()); } PackageRelationship packageRelationship = fPackage.GetRelationshipsByType("http://schemas.microsoft.com/visio/2010/relationships/document").FirstOrDefault(); PackagePart documentPart = GetPackagePart(fPackage, "http://schemas.microsoft.com/visio/2010/relationships/document"); PackagePart pagesPart = GetPackagePart(fPackage, documentPart, "http://schemas.microsoft.com/visio/2010/relationships/pages"); PackagePart pagePart = GetPackagePart(fPackage, pagesPart, "http://schemas.microsoft.com/visio/2010/relationships/page"); // Open the XML from the Page Contents part. XDocument pageXML = GetXMLFromPart(pagePart); // Get all of the shapes from the page by getting // all of the Shape elements from the pageXML document. IEnumerable <XElement> shapesXML = GetXElementsByName(pageXML, "Shape"); // Select a Shape element from the shapes on the page by // its name. You can modify this code to select elements // by other attributes and their values. XElement startEndShapeXML = GetXElementByAttribute(shapesXML, "NameU", "Shape2"); IEnumerable <XElement> textElements = from element in startEndShapeXML.Elements() where element.Name.LocalName == "Text" select element; XElement textElement = textElements.ElementAt(0); textElement.LastNode.ReplaceWith("Danny Nguyen"); // Save the XML back to the Page Contents part. SaveXDocumentToPart(pagePart, pageXML); } } catch (Exception err) { Console.WriteLine("Error: {0}", err.Message); } finally { Console.Write("\nPress any key to continue ..."); Console.ReadKey(); } }
public void Process() { CollectSignatureDefinitions(); PackageRelationshipCollection relationships = _package.GetRelationships(); ProcessRelationsips(_package, relationships); PackagePartCollection parts = _package.GetParts(); ProcessParts(parts); FixSignatureDefinitionsContentType(); }
public void AddThreeParts() { foreach (Uri u in uris) { package.CreatePart(u, "mime/type"); } Assert.AreEqual(3, package.GetParts().Count(), "Should be three parts"); PackagePartCollection c1 = package.GetParts(); package.CreatePart(new Uri("/asdasdas", UriKind.Relative), "asa/s"); PackagePartCollection c2 = package.GetParts(); bool eq = c1 == c2; Assert.IsNotNull(package.GetPart(new Uri(uris[0].ToString().ToUpper(), UriKind.Relative))); }
public void ReloadFromMemory() { Debug.Assert(memStream != null); this.docParts = null; package.Close(); package = null; package = Package.Open(memStream, FileMode.Open, FileAccess.ReadWrite); docParts = new Dictionary <string, DocumentPart>(); PackagePartCollection parts = package.GetParts(); foreach (PackagePart part in parts) { DocumentPart docPart = new DocumentPart(part); docParts.Add(part.Uri.ToString(), docPart); } }
protected override void ReadContent() { if (this._package == null) { return; } this._allText = new StringBuilder(); XmlDocument doc = null; PackagePartCollection col = this._package.GetParts(); SortedList <Int32, XmlDocument> list = new SortedList <Int32, XmlDocument>(); foreach (PackagePart part in col) { if (part.Uri.ToString().IndexOf("ppt/slides/slide", StringComparison.OrdinalIgnoreCase) > -1) { doc = new XmlDocument(); doc.Load(part.GetStream()); String pageName = part.Uri.ToString().Replace("/ppt/slides/slide", "").Replace(".xml", ""); Int32 index = 0; Int32.TryParse(pageName, out index); list.Add(index, doc); } } foreach (KeyValuePair <Int32, XmlDocument> pair in list) { XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("p", PowerPointNameSpace); XmlNode node = pair.Value.SelectSingleNode("/p:sld", nsManager); if (node == null) { continue; } this._allText.Append(NodeHelper.ReadNode(node)); } }
public static bool HasStream(string zipFilename, string partName) { if (IsValidFile(zipFilename)) { using (ZipPackage _package = (ZipPackage)Package.Open(zipFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { PackagePartCollection _packageParts = _package.GetParts(); foreach (PackagePart _part in _packageParts) { if (_part.Uri.OriginalString == '/' + partName) { Stream _st = _part.GetStream(); return(_st != null && _st.Length != 0); } } } } return(false); }
public async Task ExtractContainerAsync(string outputDirecotry, IProgress <double> progress = null, CancellationToken cancellationToken = default) { if (!Directory.Exists(outputDirecotry)) { _ = Directory.CreateDirectory(outputDirecotry); } PackagePartCollection parts = _package.GetParts(); int index = 0; int count = parts.Count(); Progress <double> innerProgress = new Progress <double> { }; innerProgress.ProgressChanged += (o, e) => { double percent = (index + e) / count; progress.Report(percent); }; if (progress == null) { innerProgress = null; } foreach (PackagePart part in parts) { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } string name = part.Uri.ToString(); string path = IOUtility.CombinePath(outputDirecotry, name); using FileStream fs = File.OpenWrite(path); await GetAsync(name, fs, innerProgress); index++; } }
/// <summary> /// Will return all the PackageParts in the Package. /// </summary> /// <remarks> /// WARNING: This implementation is based on GetParts implementations /// current behavior. We only expect to be called once on open and then /// our base implementation should handle things. /// </remarks> /// <returns>All PackageParts.</returns> protected override PackagePart[] GetPartsCore() { // need to call get parts from the underlying reading package PackagePartCollection parts = _originalPackage.Value.GetParts(); // // a temporary list of proxied package parts which will be use to fill return value List <PackagePart> _proxiedParts = new List <PackagePart>(); // for all parts not in the active list create a proxy for them // and add to active table foreach (PackagePart part in parts) { _proxiedParts.Add(GetPartCore(part.Uri)); } // return the active table PackagePart[] result = new PackagePart[_proxiedParts.Count]; _proxiedParts.CopyTo(result, 0); return(result); }
/// <summary> /// Run to read file from Open File Dialog as an XLSX file /// </summary> public ISpreadsheet ParseFromFile(string fileName) { using (var xlsxPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read)) { List <Cell> parsedCells = new List <Cell>(); PackagePartCollection allParts = xlsxPackage.GetParts(); PackagePart sharedStringsPart = allParts.Where(x => x.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml").Single(); XElement sharedStringsElement = XElement.Load(XmlReader.Create(sharedStringsPart.GetStream())); Dictionary <int, string> sharedStrings = new Dictionary <int, string>(); parseSharedStrings(sharedStringsElement, sharedStrings); XElement worksheetElement = getWorksheet(1, allParts); IEnumerable <XElement> cells = worksheetElement.Descendants(ExcelNamespaces.Main + "c"); foreach (XElement cell in cells) { string cellPosition = cell.Attribute("r").Value; int index = indexOfNumber(cellPosition); int column = getColumnNumber(cellPosition.Substring(0, index)); int row = Convert.ToInt32(cellPosition.Substring(index, cellPosition.Length - index)); if (cell.HasElements) { if (cell.Attribute("t") != null && cell.Attribute("t").Value == "s") { int valueIndex = Convert.ToInt32(cell.Descendants(ExcelNamespaces.Main + "v").Single().Value); parsedCells.Add(new Cell(column - 1, row - 1, sharedStrings[valueIndex])); } else { string value = cell.Descendants(ExcelNamespaces.Main + "v").Single().Value; parsedCells.Add(new Cell(column - 1, row - 1, value)); } } } return(new Spreadsheet(parsedCells)); } }
private static List <XDocument> GetPagePackagePartDocuments(Package filePackage) { // Get a reference to the Visio Document part contained in the file package. PackagePart documentPackagePart = GetPackagePart( filePackage, "http://schemas.microsoft.com/visio/2010/relationships/document"); // Get a reference to the collection of pages in the document, // and then to the first page in the document. PackagePart pagesPackagePart = GetPackagePartFirstOrDefault( filePackage, documentPackagePart, "http://schemas.microsoft.com/visio/2010/relationships/pages"); var pagePackageParts = GetRelatedPackageParts( filePackage, pagesPackagePart, "http://schemas.microsoft.com/visio/2010/relationships/page"); // Get all of the package parts contained in the package // and then write the URI and content type of each one to the console. PackagePartCollection packageParts = filePackage.GetParts(); //const string visionPageContentType = "application/vnd.ms-visio.page+xml"; foreach (PackagePart pagePackagePart in pagePackageParts) { Console.WriteLine("Package part URI: {0}", pagePackagePart.Uri); Console.WriteLine("Content type: {0}", pagePackagePart.ContentType); } var results = pagePackageParts .Select(pp => GetXDocumentFromPackagePart(pp)) .ToList(); return(results); }
public static void ExtractPackage(Player p) { int errors = 0; using (FileStream src = File.OpenRead(path)) using (ZipPackage zip = (ZipPackage)ZipPackage.Open(src)) { PackagePartCollection parts = zip.GetParts(); foreach (ZipPackagePart item in parts) { ExtractItem(item, ref errors); if (item.Uri.ToString().ToLower().Contains("sql.sql")) { // If it's in there, they backed it up, meaning they want it restored Backup.ReplaceDatabase(item.GetStream()); } } } // To make life easier, we reload settings now, to maker it less likely to need restart Command.all.Find("server").Use(null, "reload"); // Reload, as console Player.Message(p, "Server restored" + (errors > 0 ? " with errors. May be a partial restore" : "") + ". Restart is reccommended, though not required."); }
public string getEPCFIleText(String epcPathFile, String partFileName) { String xmlcontent = ""; using (ZipPackage package = (ZipPackage)Package.Open(epcPathFile, FileMode.Open, FileAccess.Read)) { PackagePartCollection packageParts = package.GetParts(); foreach (PackagePart packagepart in packageParts) { if (packagepart.Uri.ToString().CompareTo(partFileName) == 0) { Stream stream = null; lock (locker) { try { stream = packagepart.GetStream(FileMode.Open, FileAccess.Read); using (StreamReader reader = new StreamReader(stream)) { xmlcontent = reader.ReadToEnd(); } }catch (Exception e) { throw e; } finally { stream.Close(); } } return(xmlcontent); } } } return(null); }
/// <summary> /// Reads a session archive zip file into an array of Session objects /// </summary> /// <param name="sFilename">Filename to load</param> /// <param name="bVerboseDialogs"></param> /// <returns>Loaded array of sessions or null, in case of failure</returns> private static Session[] ReadSessionArchive(string sFilename, bool bVerboseDialogs) { /* Okay, given the zip, we gotta: * Unzip * Find all matching pairs of request, response * Create new Session object for each pair */ if (!File.Exists(sFilename)) { FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. File " + sFilename + " does not exist."); return(null); } List <Session> outSessions = new List <Session>(); try { // Sniff for ZIP file. using (FileStream oSniff = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (oSniff.Length < 64 || oSniff.ReadByte() != 0x50 || oSniff.ReadByte() != 0x4B) { // Sniff for 'PK' FiddlerApplication.Log.LogString("SAZFormat> ReadSessionArchive Failed. " + sFilename + " is not a Fiddler-generated .SAZ archive of HTTP Sessions."); return(null); } } using (Package oZip = Package.Open(sFilename, FileMode.Open)) { PackagePartCollection oAllParts = oZip.GetParts(); foreach (PackagePart oPPC in oAllParts) { string sURI = oPPC.Uri.ToString(); if (!sURI.EndsWith("_c.txt")) { continue; } byte[] arrRequest = null; byte[] arrResponse = null; // Okay, we now have a Request. Let's read it. using (Stream oData = oPPC.GetStream(FileMode.Open, FileAccess.Read)) { arrRequest = ReadEntireStream(oData); } try { sURI = sURI.Replace("_c.txt", "_s.txt"); // Get the response PackagePart oResponse = oZip.GetPart(new Uri(sURI, UriKind.Relative)); using (Stream oData = oResponse.GetStream(FileMode.Open, FileAccess.Read)) { arrResponse = ReadEntireStream(oData); } } catch (Exception eX) { FiddlerApplication.Log.LogString("Could not load Server Response: " + sURI + "\n" + eX.Message); // Fatal error. Skip this session continue; } Session oSession = new Session(arrRequest, arrResponse); oSession.oFlags["x-LoadedFrom"] = sURI; sURI = sURI.Replace("_s.txt", "_m.xml"); try { // Get the Metadata PackagePart oMetadata = oZip.GetPart(new Uri(sURI, UriKind.Relative)); Stream oData = oMetadata.GetStream(FileMode.Open, FileAccess.Read); oSession.LoadMetadata(oData); // Note: Closes the stream automatically } catch { FiddlerApplication.Log.LogString("Could not load Metadata: " + sURI); // Missing metadata is not-fatal. } outSessions.Add(oSession); } } } catch (Exception eX) { FiddlerApplication.ReportException(eX, "ReadSessionArchive Error"); return(null); } return(outSessions.ToArray()); }
// read file property in core.xml, find out the creator, datatime... // read [content_types].xml, find out the total file contains in the zip. // read _rels folder, find out the files relationship, find out the child of objects. // .rels contains define the ocreproperties. public EPCDataView readEPCFile(String epcPathFile) { // must has [content_Types].xml // /_rels/.rels must contain at least the metadata/core-properties and target. which resqml example doesnt' following. // core properties should contains creator, created, version description, id, title Dictionary <string, EPCObject> TopObjectList = new Dictionary <string, EPCObject>(); List <EPCObject> listObjects = new List <EPCObject>(); EPCCoreProperty epcCore = new EPCCoreProperty(); List <KeyValuePair <String, EPCObject> > parentChild = new List <KeyValuePair <String, EPCObject> >(); try { using (ZipPackage package = (ZipPackage)Package.Open(epcPathFile, FileMode.Open, FileAccess.Read)) { PackageRelationshipCollection packageRels = package.GetRelationships(); //package Rels must contains id "CoreProperties" property. getTargetUri directory. String sourceURI = ""; String coreURI = getCorePropertyURI(packageRels, ref sourceURI); PackagePartCollection packageParts = package.GetParts(); foreach (PackagePart packagepart in packageParts) { // match the coreURI. // find the coreProperty if ((packagepart.Uri != null) && (packagepart.Uri.Equals(sourceURI + coreURI))) { epcCore.Creator = packagepart.Package.PackageProperties.Creator; epcCore.Created = packagepart.Package.PackageProperties.Created; epcCore.Version = packagepart.Package.PackageProperties.Version; epcCore.Description = packagepart.Package.PackageProperties.Description; epcCore.Identifier = packagepart.Package.PackageProperties.Identifier; epcCore.Keywords = packagepart.Package.PackageProperties.Keywords; epcCore.Title = packagepart.Package.PackageProperties.Title; } else { // create each epcobject for package part if (isPart(packagepart)) { EPCObject epcObject = new EPCObject(); String epcContentType = ""; String version = ""; String epcObjectType = ""; EPCPartValidator.parseContentType(packagepart.ContentType, ref epcContentType, ref version, ref epcObjectType); epcObject.EpcContentType = epcContentType; epcObject.EPCObjectType = epcObjectType; epcObject.SchemaVersion = version; epcObject.PackageFile = epcPathFile; epcObject.EpcFileName = this.getfilename(packagepart.Uri.ToString()); epcObject.Uuid = this.getuuid(packagepart.Uri.ToString()); epcObject.Uri = packagepart.Uri; listObjects.Add(epcObject); //get rest relationship items PackageRelationshipCollection partRels = null; try { if (packagepart != null) { partRels = packagepart.GetRelationships(); } } catch (Exception e) { Console.WriteLine("warning : " + e.Message); } if (partRels != null) { // create pair key for relationships parent and child foreach (PackageRelationship partsRel in partRels) { EPCRelationshipType epcrelType = EPCPartValidator.getRelationshipType(partsRel.RelationshipType); // conver the target and source into the parent and child table. if ((epcrelType == EPCRelationshipType.destinationObject) || (epcrelType == EPCRelationshipType.mlToExternalPartProxy) || (epcrelType == EPCRelationshipType.destinationMedia) || (epcrelType == EPCRelationshipType.externalResource) || (epcrelType == EPCRelationshipType.chunkedPart) ) { string name = getfilename(packagepart.Uri.ToString()); //string childname = getfilename(partsRel.TargetUri.ToString()); EPCObject obj = new EPCObject(); obj.TargetMode = partsRel.TargetMode;; obj.EpcFileName = partsRel.TargetUri.ToString(); if ((obj.TargetMode == TargetMode.External) && (obj.EpcFileName.EndsWith(".h5"))) { obj.HDF5 = true; epcObject.EpcFileName = obj.EpcFileName; epcObject.HDF5 = true; } KeyValuePair <string, EPCObject> pair = new KeyValuePair <string, EPCObject>(name, obj); if (!isDuplicated(parentChild, pair)) { parentChild.Add(pair); } //else //Console.WriteLine("source already add in. skip ..."); } if ((epcrelType == EPCRelationshipType.sourceObject) || (epcrelType == EPCRelationshipType.extenalPartProxyToMI) || (epcrelType == EPCRelationshipType.sourceMedia)) { string name = getfilename(partsRel.TargetUri.ToString()); string childname = getfilename(packagepart.Uri.ToString()); EPCObject obj = new EPCObject(); obj.TargetMode = partsRel.TargetMode;; obj.EpcFileName = childname; KeyValuePair <string, EPCObject> pair = new KeyValuePair <string, EPCObject>(name, obj); if (!isDuplicated(parentChild, pair)) { parentChild.Add(pair); } //else //Console.WriteLine("source already add in. skip ..."); } } } } } } //sort the hierachy from the pair listObjects.Sort(new EPCObjectComparer()); TopObjectList = sortHierarchy(parentChild, listObjects); // assign to dataviewer. EPCDataView dataviewer = new EPCDataView(); dataviewer.TopObjectList = TopObjectList; dataviewer.ListObjects = listObjects; dataviewer.EpcCoreProperty = epcCore; return(dataviewer); } }catch (Exception e) { throw new Exception(String.Format("the file is not validate EPC file : {0} ", e.Message)); } }
/// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, Func <Uri, bool> excludeMethod, out string message) { #region Check if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } #endregion excludeMethod = excludeMethod ?? (uri => false); PackagePartCollection leftParts = left.GetParts(); PackagePartCollection rightParts = right.GetParts(); var pairs = new Dictionary <Uri, PartPair>(); foreach (PackagePart part in leftParts) { if (excludeMethod(part.Uri)) { continue; } pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnLeft)); } foreach (PackagePart part in rightParts) { if (excludeMethod(part.Uri)) { continue; } PartPair pair; if (pairs.TryGetValue(part.Uri, out pair)) { pair.Status = CompareStatus.Equal; } else { pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnRight)); } } if (compareToFirstDifference && pairs.Any(pair => pair.Value.Status != CompareStatus.Equal)) { goto EXIT; } foreach (PartPair pair in pairs.Values) { if (pair.Status != CompareStatus.Equal) { continue; } using (Stream oneStream = left.GetPart(pair.Uri).GetStream(FileMode.Open, FileAccess.Read)) using (Stream otherStream = right.GetPart(pair.Uri).GetStream(FileMode.Open, FileAccess.Read)) { if (!StreamHelper.Compare(oneStream, otherStream)) { pair.Status = CompareStatus.NonEqual; if (compareToFirstDifference) { goto EXIT; } } } } EXIT: List <PartPair> sortedPairs = pairs.Values.ToList(); sortedPairs.Sort((one, other) => one.Uri.OriginalString.CompareTo(other.Uri.OriginalString)); var sbuilder = new StringBuilder(); foreach (PartPair pair in sortedPairs) { if (pair.Status == CompareStatus.Equal) { continue; } sbuilder.AppendFormat("{0} :{1}", pair.Uri, pair.Status); sbuilder.AppendLine(); } message = sbuilder.ToString(); return(message.Length == 0); }
public static int ExtractFiles(string packagefile, string destFolder) { //extract the package content to temp folder string tempfolder = Path.Combine(destFolder, Path.GetFileNameWithoutExtension(packagefile)); // Path.GetFileNameWithoutExtension(fileFullPath) if (Directory.Exists(tempfolder)) { Directory.Delete(tempfolder, true); //Wait till folder is deleted Thread.Sleep(1000); } Directory.CreateDirectory(tempfolder); try { using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@packagefile, FileMode.Open, FileAccess.Read, FileShare.Read)) { PackageRelationshipCollection relationships = ABpackage.GetRelationships(); PackagePartCollection parts = ABpackage.GetParts(); List <ZipEntry> files = GetPackageFile(packagefile); if (files.Count() - 1 != parts.Count()) //[Content_Types].xml is not considered as file part { if (files.Count() - 1 > parts.Count()) { Console.WriteLine(String.Format("Package {0} is corrupt. Additional files found", packagefile)); return(-1); } else if (files.Count() - 1 < parts.Count()) { Console.WriteLine(String.Format("Package {0} is corrupt. Some files are missing", packagefile)); return(-1); } } List <PackagePart> originalParts = new List <PackagePart>(); foreach (PackagePart item in parts) { if ((item.ContentType == "application/vnd.openxmlformats-package.relationships+xml") || (item.ContentType == "application/vnd.openxmlformats-package.digital-signature-origin") || (item.ContentType == "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml")) { } else { originalParts.Add(item); } } //if (originalParts.Count != relationships.Count() - 1) //{ // if (originalParts.Count > relationships.Count() - 1) // { // // ErrorBase.WriteToLog(String.Format("Package {0} is corrupt. Additional files found", packagefile)); // return -1; // } // else if (originalParts.Count > relationships.Count() - 1) // { // //ErrorBase.WriteToLog(String.Format("Package {0} is corrupt. Some files are missing", packagefile)); // return -1; // } //} foreach (PackageRelationship rel in relationships) { PackagePart packagePart = ABpackage.GetPart(rel.TargetUri); if (!packagePart.ContentType.Contains("part/")) { continue; } string lastModified = String.Empty; ZipEntry entry = files.Find(e => e.Name.Equals(packagePart.Uri.ToString().TrimStart('/'), StringComparison.InvariantCultureIgnoreCase)); if (entry == null) { continue; } //prepare file path information string partRelativePath = Uri.UnescapeDataString(packagePart.Uri.ToString()); //partRelativePath = (partRelativePath.TrimStart('/')).Replace("%20", " "); //partRelativePath = partRelativePath.Replace("%7b", "{"); //partRelativePath = partRelativePath.Replace("%7d", "}"); //partRelativePath = partRelativePath.Replace("%7B", "{"); //partRelativePath = partRelativePath.Replace("%7D", "}"); //partRelativePath = partRelativePath.Replace("%C2%A0", " "); //partRelativePath = partRelativePath.Replace("%C3%84", "Ä"); //partRelativePath = partRelativePath.Replace("%C3%A4", "ä"); //partRelativePath = partRelativePath.Replace("%C3%96", "Ö"); //partRelativePath = partRelativePath.Replace("%C3%B6", "ö"); //partRelativePath = partRelativePath.Replace("%C3%9C", "Ü"); //partRelativePath = partRelativePath.Replace("%C3%BC", "ü"); //partRelativePath = partRelativePath.Replace("%C3%9F", "ß"); //partRelativePath = partRelativePath.Replace("/", "\\"); string absolutePath = Path.Combine(tempfolder, partRelativePath.TrimStart('/')); if (!Directory.Exists(Path.GetDirectoryName(absolutePath))) { Directory.CreateDirectory(Path.GetDirectoryName(absolutePath)); } FileInfo extractFileInfo = new FileInfo(absolutePath); //Hp --> Logic: Check if the zip entry is older than the file system version //if yes don't overwrite the file system version. if ((extractFileInfo.Exists) && (DateTime.Compare(extractFileInfo.LastWriteTime, entry.DateTime) >= 0)) { continue; } // Create the file with the Part content using (FileStream fileStream = new FileStream(absolutePath, FileMode.Create)) { //ErrorBase.WriteToLog("Extracting file: " + absolutePath); try { packagePart.GetStream().CopyTo(fileStream); } catch (Exception ex) { //ErrorBase.WriteToLog(ex.Message); return(1); } } extractFileInfo.Refresh(); //Hp --> Always remove ReadOnly file attribute extractFileInfo.Attributes &= ~FileAttributes.ReadOnly; //set creation and modification date to zipped file date extractFileInfo.CreationTime = entry.DateTime; extractFileInfo.LastWriteTime = entry.DateTime; } } return(1); } catch (Exception ex) { //ErrorBase.WriteToLog(packagefile + "extraction encountered an exception." + ex.Message); //ErrorBase.WriteToLog("Cleanup extracted files / folders..."); if (Directory.Exists(tempfolder)) { Directory.Delete(tempfolder, true); //Wait till folder is deleted Thread.Sleep(1000); } return(-1); } }
/** * Load the parts of the archive if it has not been done yet. The * relationships of each part are not loaded. * Note - Rule M4.1 states that there may only ever be one Core * Properties Part, but Office produced files will sometimes * have multiple! As Office ignores all but the first, we relax * Compliance with Rule M4.1, and ignore all others silently too. * @return All this package's parts. */ public List<PackagePart> GetParts() { ThrowExceptionIfWriteOnly(); // If the part list is null, we parse the package to retrieve all parts. if (partList == null) { /* Variables use to validate OPC Compliance */ // Check rule M4.1 -> A format consumer shall consider more than // one core properties relationship for a package to be an error // (We just log it and move on, as real files break this!) bool hasCorePropertiesPart = false; bool needCorePropertiesPart = true; PackagePart[] parts = this.GetPartsImpl(); this.partList = new PackagePartCollection(); foreach (PackagePart part in parts) { bool pnFound = false; foreach (PackagePartName pn in partList.Keys) { if (part.PartName.Name.StartsWith(pn.Name)) { pnFound = true; break; } } if (pnFound) throw new InvalidFormatException( "A part with the name '" + part.PartName + "' already exist : Packages shall not contain equivalent " + "part names and package implementers shall neither create " + "nor recognize packages with equivalent part names. [M1.12]"); // Check OPC compliance rule M4.1 if (part.ContentType.Equals( ContentTypes.CORE_PROPERTIES_PART)) { if (!hasCorePropertiesPart) hasCorePropertiesPart = true; else Console.WriteLine( "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package ! " + "POI will use only the first, but other software may reject this file."); } if (partUnmarshallers.ContainsKey(part.contentType)) { PartUnmarshaller partUnmarshaller = partUnmarshallers[part.contentType]; UnmarshallContext context = new UnmarshallContext(this, part.PartName); try { PackagePart unmarshallPart = partUnmarshaller .Unmarshall(context, part.GetInputStream()); partList[unmarshallPart.PartName] = unmarshallPart; // Core properties case-- use first CoreProperties part we come across // and ignore any subsequent ones if (unmarshallPart is PackagePropertiesPart && hasCorePropertiesPart && needCorePropertiesPart) { this.packageProperties = (PackagePropertiesPart)unmarshallPart; needCorePropertiesPart = false; } } catch (IOException) { logger.Log(POILogger.WARN, "Unmarshall operation : IOException for " + part.PartName); continue; } catch (InvalidOperationException invoe) { throw new InvalidFormatException(invoe.Message); } } else { try { partList[part.PartName] = part; } catch (InvalidOperationException e) { throw new InvalidFormatException(e.Message); } } } } return new List<PackagePart>(partList.Values); }
/// <summary> /// This returns a collection of all the Parts within the package. /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">If this Package object has been disposed</exception> /// <exception cref="IOException">If the package is writeonly, no information can be retrieved from it</exception> public PackagePartCollection GetParts() { ThrowIfObjectDisposed(); ThrowIfWriteOnly(); //Ideally we should decide whether we should query the underlying layer for parts based on the //FileShare enum. But since we do not have that information, currently the design is to just //query the underlying layer once. //Note: //Currently the incremental behavior for GetPart method is not consistent with the GetParts method //which just queries the underlying layer once. if (_partCollection == null) { PackagePart[] parts = GetPartsCore(); //making sure that we get a valid array Debug.Assert((parts != null), "Subclass is expected to return an array [an empty one if there are no parts] as a result of GetPartsCore method call. "); PackUriHelper.ValidatedPartUri partUri; //We need this dictionary to detect any collisions that might be present in the //list of parts that was given to us from the underlying physical layer, as more than one //partnames can be mapped to the same normalized part. //Note: We cannot use the _partList member variable, as that gets updated incrementally and so its //not possible to find the collisions using that list. //PackUriHelper.ValidatedPartUri implements the IComparable interface. Dictionary<PackUriHelper.ValidatedPartUri, PackagePart> seenPartUris = new Dictionary<PackUriHelper.ValidatedPartUri, PackagePart>(parts.Length); for (int i = 0; i < parts.Length; i++) { partUri = (PackUriHelper.ValidatedPartUri)parts[i].Uri; if (seenPartUris.ContainsKey(partUri)) throw new FileFormatException(SR.BadPackageFormat); else { // Add the part to the list of URIs that we have already seen seenPartUris.Add(partUri, parts[i]); if (!_partList.ContainsKey(partUri)) { // Add the part to the _partList if there is no prefix collision AddIfNoPrefixCollisionDetected(partUri, parts[i]); } } } _partCollection = new PackagePartCollection(_partList); } return _partCollection; }
/// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, Func <Uri, bool> excludeMethod, out string message) { #region Check if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } #endregion Check excludeMethod = excludeMethod ?? (uri => false); PackagePartCollection leftParts = left.GetParts(); PackagePartCollection rightParts = right.GetParts(); var pairs = new Dictionary <Uri, PartPair>(); foreach (PackagePart part in leftParts) { if (excludeMethod(part.Uri)) { continue; } pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnLeft)); } foreach (PackagePart part in rightParts) { if (excludeMethod(part.Uri)) { continue; } PartPair pair; if (pairs.TryGetValue(part.Uri, out pair)) { pair.Status = CompareStatus.Equal; } else { pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnRight)); } } if (compareToFirstDifference && pairs.Any(pair => pair.Value.Status != CompareStatus.Equal)) { goto EXIT; } foreach (PartPair pair in pairs.Values) { if (pair.Status != CompareStatus.Equal) { continue; } var leftPart = left.GetPart(pair.Uri); var rightPart = right.GetPart(pair.Uri); using (Stream leftPackagePartStream = leftPart.GetStream(FileMode.Open, FileAccess.Read)) using (Stream rightPackagePartStream = rightPart.GetStream(FileMode.Open, FileAccess.Read)) using (var leftMemoryStream = new MemoryStream()) using (var rightMemoryStream = new MemoryStream()) { leftPackagePartStream.CopyTo(leftMemoryStream); rightPackagePartStream.CopyTo(rightMemoryStream); leftMemoryStream.Seek(0, SeekOrigin.Begin); rightMemoryStream.Seek(0, SeekOrigin.Begin); bool stripColumnWidthsFromSheet = TestHelper.StripColumnWidths && leftPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" && rightPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"; var tuple1 = new Tuple <Uri, Stream>(pair.Uri, leftMemoryStream); var tuple2 = new Tuple <Uri, Stream>(pair.Uri, rightMemoryStream); if (!StreamHelper.Compare(tuple1, tuple2, stripColumnWidthsFromSheet)) { pair.Status = CompareStatus.NonEqual; if (compareToFirstDifference) { goto EXIT; } } } } EXIT: List <PartPair> sortedPairs = pairs.Values.ToList(); sortedPairs.Sort((one, other) => one.Uri.OriginalString.CompareTo(other.Uri.OriginalString)); var sbuilder = new StringBuilder(); foreach (PartPair pair in sortedPairs) { if (pair.Status == CompareStatus.Equal) { continue; } sbuilder.AppendFormat("{0} :{1}", pair.Uri, pair.Status); sbuilder.AppendLine(); } message = sbuilder.ToString(); return(message.Length == 0); }