GetParts() public method

public GetParts ( ) : PackagePartCollection
return PackagePartCollection
Example #1
0
 private static void CopyPackage(Package inputPackage, Package outputPackage)
 {
     foreach (var inputPart in inputPackage.GetParts())
     {
         CreateNewPart(inputPart, outputPackage);
     }
 }
        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;
            }
        }
Example #3
0
        private Package Sign(Package package)
        {
            foreach (var packagePart in package.GetParts())
            {
                SignPackagePart(packagePart);
            }

            return package;
        }
Example #4
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="package">package to filter</param>
        internal PackageFilter(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            _package = package;
            _partIterator = _package.GetParts().GetEnumerator();
        }
Example #5
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="package">package to filter</param>
        internal PackageFilter(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            _package      = package;
            _partIterator = _package.GetParts().GetEnumerator();
        }
Example #6
0
        /// <summary>
        /// Load all parts
        /// </summary>
        private void LoadAll(System.IO.Packaging.Package package)
        {
            var sharedObjectCache = new Dictionary <string, byte[]>();

            foreach (var part in package.GetParts().Where(x => !IsSharedObject(x.Uri)))
            {
                // Load the part's content and store it.
                var bytes = GetPartContent(package, part, sharedObjectCache);
                parts[part.Uri] = bytes;
            }
        }
Example #7
0
        private static void SignAllParts(Package package)
        {
            if (package == null)
                throw new ArgumentNullException("SignAllParts(package)");

            // Create the DigitalSignature Manager
            PackageDigitalSignatureManager dsm =
                new PackageDigitalSignatureManager(package);
            dsm.CertificateOption =
                CertificateEmbeddingOption.InSignaturePart;

            // Create a list of all the part URIs in the package to sign
            // (GetParts() also includes PackageRelationship parts).
            System.Collections.Generic.List<Uri> toSign =
                new System.Collections.Generic.List<Uri>();
            foreach (PackagePart packagePart in package.GetParts())
            {
                // Add all package parts to the list for signing.
                toSign.Add(packagePart.Uri);
            }

            // Add the URI for SignatureOrigin PackageRelationship part.
            // The SignatureOrigin relationship is created when Sign() is called.
            // Signing the SignatureOrigin relationship disables counter-signatures.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

            // Also sign the SignatureOrigin part.
            toSign.Add(dsm.SignatureOrigin);

            // Add the package relationship to the signature origin to be signed.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

            // Sign() will prompt the user to select a Certificate to sign with.
            try
            {
                dsm.Sign(toSign);
            }

            // If there are no certificates or the SmartCard manager is
            // not running, catch the exception and show an error message.
            catch (CryptographicException ex)
            {
                MessageBox.Show(
                    "Cannot Sign\n" + ex.Message,
                    "No Digital Certificates Available",
                    MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);
            }
        }
Example #8
0
        /// <summary>
        /// Main signing process
        /// </summary>
        /// <param name="package"></param>
        /// <returns></returns>
        private bool SignAllParts(Package package)
        {
            if (package == null)
                throw new ArgumentNullException("SignAllParts(package)");

            // Create the DigitalSignature Manager
            PackageDigitalSignatureManager dsm =
                new PackageDigitalSignatureManager(package);
            dsm.CertificateOption =
                CertificateEmbeddingOption.InSignaturePart;

            // Create a list of all the part URIs in the package to sign
            // (GetParts() also includes PackageRelationship parts).
            System.Collections.Generic.List<Uri> toSign =
                new System.Collections.Generic.List<Uri>();
            foreach (PackagePart packagePart in package.GetParts())
            {
                // Add all package parts to the list for signing.
                toSign.Add(packagePart.Uri);
            }

            // Add the URI for SignatureOrigin PackageRelationship part.
            // The SignatureOrigin relationship is created when Sign() is called.
            // Signing the SignatureOrigin relationship disables counter-signatures.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

            // Also sign the SignatureOrigin part.
            toSign.Add(dsm.SignatureOrigin);

            // Add the package relationship to the signature origin to be signed.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

            // Sign() will prompt the user to select a Certificate to sign with.
            try
            {
                var cert = new X509Certificate2(this.CertificatePath, (String.IsNullOrEmpty(this.CertificatePassword) ? null : this.CertificatePassword));
                dsm.Sign(toSign, cert);
            }

            // If there are no certificates or the SmartCard manager is
            // not running, catch the exception and show an error message.
            catch (CryptographicException ex)
            {
                Console.WriteLine(
                    "Cannot Sign: {0}", ex.Message);
            }

            return dsm.IsSigned && dsm.VerifySignatures(true) == VerifyResult.Success;
        }
Example #9
0
 private void UnzipTo(Package package, string outPath)
 {
     var packageParts=package.GetParts();
     foreach (PackagePart part in packageParts)
     {
         string outFileName = Path.Combine(outPath, part.Uri.OriginalString.Substring(1));
         using (FileStream outFileStream = new FileStream(outFileName, FileMode.Create))
         {
             using (Stream inFileStream = part.GetStream())
             {
                 CopyStream(inFileStream, outFileStream);
             }
         }
     }
 }
Example #10
0
        /// <summary>
        ///By package because  ChangeDocumentType not working well
        /// </summary>
        /// <param name="documentStream"></param>
        private void ChangeDocmToDocxUsingPackage(Stream documentStream)
        {
            // Open the document in the stream and replace the custom XML part
            using (System.IO.Packaging.Package packageFile = System.IO.Packaging.Package.Open(documentStream, FileMode.Open, FileAccess.ReadWrite))
            {
                System.IO.Packaging.PackagePart packagePart = null;
                // Find part containing the correct namespace
                foreach (var part in packageFile.GetParts())
                {
                    if (part.ContentType.Equals("application/vnd.ms-word.document.macroEnabled.main+xml", StringComparison.OrdinalIgnoreCase))
                    {
                        packagePart = part;
                        break;
                    }
                }
                if (packagePart != null)
                {
                    using (MemoryStream source = new MemoryStream())
                    {
                        CopyStream(packagePart.GetStream(), source);

                        var saveRelationBeforeDelPart = new List <PackageRelationship>();
                        foreach (var item in packagePart.GetRelationships())
                        {
                            saveRelationBeforeDelPart.Add(item);
                        }

                        Uri uriData = packagePart.Uri;
                        // Delete the existing XML part
                        if (packageFile.PartExists(uriData))
                        {
                            packageFile.DeletePart(uriData);
                        }

                        // Load the custom XML data
                        var pkgprtData = packageFile.CreatePart(uriData, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", System.IO.Packaging.CompressionOption.SuperFast);

                        source.Position = 0;//reset position
                        CopyStream(source, pkgprtData.GetStream(FileMode.Create));

                        foreach (var copyRel in saveRelationBeforeDelPart)
                        {
                            pkgprtData.CreateRelationship(copyRel.TargetUri, copyRel.TargetMode, copyRel.RelationshipType, copyRel.Id);
                        }
                    }
                }
            }
        }
Example #11
0
 void VerifyPartsAreTheSame(Package package1, Package package2)
 {
     foreach (var part1 in package1.GetParts())
     {
         if (part1.Uri.OriginalString.EndsWith("psmdcp"))
         {
             continue;
         }
         if (part1.Uri.OriginalString.EndsWith("rels"))
         {
             continue;
         }
         var part2 = package2.GetPart(part1.Uri);
         var hash1 = GetFileHash(part1);
         var hash2 = GetFileHash(part2);
         Assert.AreEqual(hash1, hash2, part1.Uri.OriginalString);
     }
 }
Example #12
0
        /// <summary>
        /// If this document does not contain a /word/numbering.xml add the default one generated by Microsoft Word 
        /// when the default bullet, numbered and multilevel lists are added to a blank document
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultNumberingXml(Package package)
        {
            XDocument numberingDoc;
            // Create the main document part for this package
            PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);

            numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");

            // Save /word/numbering.xml
            using (TextWriter tw = new StreamWriter(wordNumbering.GetStream(FileMode.Create, FileAccess.Write)))
                numberingDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                          p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

            mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
            return numberingDoc;
        }
Example #13
0
        /// <summary>
        /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultStylesXml(Package package)
        {
            XDocument stylesDoc;
            // Create the main document part for this package
            PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);

            stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
            XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName));
            lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

            // Save /word/styles.xml
            using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write)))
                stylesDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Where
            (
                p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)||p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
            ).Single();

            mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
            return stylesDoc;
        }
Example #14
0
        private void WriteFiles(Package package)
        {
            // Add files that might not come from expanding files on disk
            foreach (IPackageFile file in new HashSet<IPackageFile>(Files))
            {
                using (Stream stream = file.GetStream())
                {
                    try
                    {
                        CreatePart(package, file.Path, stream);
                    }
                    catch 
                    {
                        Console.WriteLine(file.Path);
                        throw;
                    }
                }
            }

            foreach (var file in package.GetParts().GroupBy(s => s.Uri).Where(_ => _.Count() > 1))
            {
                Console.WriteLine(file.Key);
            }
        }
Example #15
0
 protected virtual void ProcessPackageContents(Package package)
 {
     Files = package.GetParts()
         .Where(p => !PackageFileExcludeExtensions.Contains(Path.GetExtension(p.Uri.OriginalString)))
         .Select(p => new FastZipPackageFile(this, p.Uri.OriginalString))
         .ToArray();
 }
Example #16
0
        internal static DocX PostLoad(ref Package package)
        {
            DocX document = new DocX(null, null);
            document.package = package;
            document.Document = document;

            #region MainDocumentPart
            document.mainPart = package.GetParts().Where
            (
                p => p.ContentType.Equals
                (
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                    StringComparison.CurrentCultureIgnoreCase
                )
            ).Single();

            using (TextReader tr = new StreamReader(document.mainPart.GetStream(FileMode.Open, FileAccess.Read)))
                document.mainDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
            #endregion

            PopulateDocument(document, package);

            using (TextReader tr = new StreamReader(document.settingsPart.GetStream()))
                document.settings = XDocument.Load(tr);

            return document;
        }
        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);
            }
        }
Example #18
0
 /// <summary>
 /// Returns an XDocument
 /// </summary>
 /// <param name="package">System.IO.Packaging.Package</param>
 /// <returns></returns>
 public static XDocument OpcToFlatOpc(Package package)
 {
     XNamespace 
         pkg = "http://schemas.microsoft.com/office/2006/xmlPackage";
     XDeclaration 
         declaration = new XDeclaration("1.0", "UTF-8", "yes");
     XDocument doc = new XDocument(
         declaration,
         new XProcessingInstruction("mso-application", "progid=\"Word.Document\""),
         new XElement(pkg + "package",
             new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
             package.GetParts().Select(part => GetContentsAsXml(part))
         )
     );
     return doc;
 }
Example #19
0
        internal static PackagePart CreateOrGetSettingsPart(Package package)
        {
            PackagePart settingsPart;

            Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
            if (!package.PartExists(settingsUri))
            {
                settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);

                PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                              p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

                mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");

                XDocument settings = XDocument.Parse
                (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
                <w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
                  <w:zoom w:percent='100' />
                  <w:defaultTabStop w:val='720' />
                  <w:characterSpacingControl w:val='doNotCompress' />
                  <w:compat />
                  <w:rsids>
                    <w:rsidRoot w:val='00217F62' />
                    <w:rsid w:val='001915A3' />
                    <w:rsid w:val='00217F62' />
                    <w:rsid w:val='00A906D8' />
                    <w:rsid w:val='00AB5A74' />
                    <w:rsid w:val='00F071AE' />
                  </w:rsids>
                  <m:mathPr>
                    <m:mathFont m:val='Cambria Math' />
                    <m:brkBin m:val='before' />
                    <m:brkBinSub m:val='--' />
                    <m:smallFrac m:val='off' />
                    <m:dispDef />
                    <m:lMargin m:val='0' />
                    <m:rMargin m:val='0' />
                    <m:defJc m:val='centerGroup' />
                    <m:wrapIndent m:val='1440' />
                    <m:intLim m:val='subSup' />
                    <m:naryLim m:val='undOvr' />
                  </m:mathPr>
                  <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
                  <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
                  <w:shapeDefaults>
                    <o:shapedefaults v:ext='edit' spidmax='2050' />
                    <o:shapelayout v:ext='edit'>
                      <o:idmap v:ext='edit' data='1' />
                    </o:shapelayout>
                  </w:shapeDefaults>
                  <w:decimalSymbol w:val='.' />
                  <w:listSeparator w:val=',' />
                </w:settings>"
                );

                XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
                themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

                // Save the settings document.
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
                    settings.Save(tw);
            }
            else
                settingsPart = package.GetPart(settingsUri);
            return settingsPart;
        }
Example #20
0
        private static void PopulateDocument(DocX document, Package package)
        {
            Headers headers = new Headers();
            headers.odd = document.GetHeaderByType("default");
            headers.even = document.GetHeaderByType("even");
            headers.first = document.GetHeaderByType("first");

            Footers footers = new Footers();
            footers.odd = document.GetFooterByType("default");
            footers.even = document.GetFooterByType("even");
            footers.first = document.GetFooterByType("first");

            //// Get the sectPr for this document.
            //XElement sect = document.mainDoc.Descendants(XName.Get("sectPr", DocX.w.NamespaceName)).Single();

            //if (sectPr != null)
            //{
            //    // Extract the even header reference
            //    var header_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id = header_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res = document.mainPart.GetRelationship(id);
            //    string ans = res.SourceUri.OriginalString;
            //    headers.even.xml_filename = ans;

            //    // Extract the odd header reference
            //    var header_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id2 = header_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res2 = document.mainPart.GetRelationship(id2);
            //    string ans2 = res2.SourceUri.OriginalString;
            //    headers.odd.xml_filename = ans2;

            //    // Extract the first header reference
            //    var header_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "h
            //eaderReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id3 = header_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res3 = document.mainPart.GetRelationship(id3);
            //    string ans3 = res3.SourceUri.OriginalString;
            //    headers.first.xml_filename = ans3;

            //    // Extract the even footer reference
            //    var footer_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id4 = footer_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res4 = document.mainPart.GetRelationship(id4);
            //    string ans4 = res4.SourceUri.OriginalString;
            //    footers.even.xml_filename = ans4;

            //    // Extract the odd footer reference
            //    var footer_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id5 = footer_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res5 = document.mainPart.GetRelationship(id5);
            //    string ans5 = res5.SourceUri.OriginalString;
            //    footers.odd.xml_filename = ans5;

            //    // Extract the first footer reference
            //    var footer_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id6 = footer_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res6 = document.mainPart.GetRelationship(id6);
            //    string ans6 = res6.SourceUri.OriginalString;
            //    footers.first.xml_filename = ans6;

            //}

            document.Xml = document.mainDoc.Root.Element(w + "body");
            document.headers = headers;
            document.footers = footers;
            document.settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);

            var ps = package.GetParts();

            //document.endnotesPart = HelperFunctions.GetPart();

            foreach (var rel in document.mainPart.GetRelationships())
            {
                switch (rel.RelationshipType)
                {
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes":
                        document.endnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.endnotesPart.GetStream()))
                            document.endnotes = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes":
                        document.footnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.footnotesPart.GetStream()))
                            document.footnotes = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles":
                        document.stylesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.stylesPart.GetStream()))
                            document.styles = XDocument.Load(tr);
                        break;

                    case "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects":
                        document.stylesWithEffectsPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.stylesWithEffectsPart.GetStream()))
                            document.stylesWithEffects = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable":
                        document.fontTablePart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.fontTablePart.GetStream()))
                            document.fontTable = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering":
                        document.numberingPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.numberingPart.GetStream()))
                            document.numbering = XDocument.Load(tr);
                        break;

                    default:
                        break;
                }
            }
        }
Example #21
0
        internal static DocX PostLoad(ref Package package)
        {
            DocX document = new DocX(null, null);
            document.package = package;
            document.Document = document;

            #region MainDocumentPart
            document.mainPart = package.GetParts().Where
            (
                     p => p.ContentType.Equals(HelperFunctions.DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                     p.ContentType.Equals(HelperFunctions.TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
            ).Single();

            using (TextReader tr = new StreamReader(document.mainPart.GetStream(FileMode.Open, FileAccess.Read)))
                document.mainDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
            #endregion

            PopulateDocument(document, package);

            using (TextReader tr = new StreamReader(document.settingsPart.GetStream()))
                document.settings = XDocument.Load(tr);

            document.paragraphLookup.Clear();
            foreach (var paragraph in document.Paragraphs)
            {
                if (!document.paragraphLookup.ContainsKey(paragraph.endIndex))
                    document.paragraphLookup.Add(paragraph.endIndex, paragraph);
            }
            
            return document;
        }
Example #22
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);
            }
        }