0

I am trying to delete/remove custom properties from a word document, the document is corrupted. This is my code so far. I compiles correctly, but does not open.

public static MemoryStream DeleteCustomPropertiers(Stream fileStream)
        {
            var msStream = new MemoryStream();
            fileStream.CopyTo(msStream);
            using (var document = WordprocessingDocument.Open(msStream, true))
            {
                var properties = new Dictionary<string, string>();
                if (document != null)
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps != null)
                    {
                        if (customProps.Properties != null)
                        {
                            var props = from n in customProps.Properties.Elements<CustomDocumentProperty>()
                                        where n.Name == "Props1" || n.Name == "Props2"
                                        select n;

                            for (int i = props.Count() - 1; i >= 0; i--)
                            {
                                var prop = props.ToList()[i];
                                prop.Remove();
                            }
                            customProps.Properties.Save();
                        }
                    }
                }
                msStream.Position = 0;
            document.MainDocumentPart.Document.Save();
            document.Dispose();
                return msStream;
            }
        }

OK, I disposed the document, but I am still getting the error:

Word found unreadable content in ''. Do you want to recover the contents of this docuemtn? if you trust the source of this document, click yes
  • Close and dispose your document. See https://stackoverflow.com/a/76016903 and https://stackoverflow.com/questions/48267165. You might also want to reset your mStream to position 0 so callers of your method can start reading immediately, otherwise they find themselves at the end of the stream with nothing more to do. – rene Apr 18 '23 at 07:09
  • I disposed the document and set the position to 0, but I still get the error. See my Edit in my original post. – user20377051 Apr 18 '23 at 09:41
  • `msStream.Position = 0;` needs to be the last call before you return – rene Apr 18 '23 at 09:45
  • Can't you do customProps.Properties.RemoveChild(prop); instead of prop.Remove(); ? – rene Apr 18 '23 at 09:52
  • it works just fine in a console application, but on the site it does not work. – user20377051 Apr 18 '23 at 10:08
  • add `msStream.Position = 0;` right after `fileStream.CopyTo(msStream);` – rene Apr 18 '23 at 10:16
  • I added msStream.Position = 0; right before the return and it worked – user20377051 Apr 18 '23 at 17:19

0 Answers0