2

After replacing the image (deleting and copying in the new image of the same name and extension) the altered .docx file won't open.

The error message I receive from MS Word: Microsoft Office cannot open this file because some parts are missing or invalid.

This method works manually, unzipping, adding the image into the media folder, re-zipping.

Problem line:

ZipFile.CreateFromDirectory(extractpath, newDoc,CompressionLevel.Optimal, true);

As the manual method is working, I think that the above line is causing the issue, am I doing something wrong or is there a preferred method of re-zipping?

Full Code:

string ImagePath = @"\word\media";
            string oldImage = @"\image1.png";
            string newImage = @"C:\Users\per\Desktop\ReBrander\TemplateImage\TODOJO.png";
            string ep = @"C:\Users\per\Desktop\ReBrander\Current";
            string newDoc = ep + @"\ImageChanged.docx";
            string doc = @"C:\Users\per\Desktop\ReBrander\OldDocuments\TestDoc.docx";
            string extractpath = @"C:\Users\per\Desktop\ReBrander\TmpDmp";

            try
            {
                ZipFile.ExtractToDirectory(doc, extractpath);

                string[] filePaths = Directory.GetFiles(extractpath + ImagePath);
                foreach (string fp in filePaths)
                {
                    File.Delete(fp);
                }

                File.Copy(newImage, extractpath + ImagePath + oldImage);

                ZipFile.CreateFromDirectory(extractpath, newDoc,CompressionLevel.Optimal, true);

                return true;
            }
            catch
            {
                return false;
            }
PurpleSmurph
  • 2,055
  • 3
  • 32
  • 52
  • 1
    Have a look here: http://stackoverflow.com/questions/1514052/how-to-zip-a-wordprocessingml-folder-into-readable-docx – JaggenSWE Jan 19 '16 at 14:39
  • Any reason you've decided not to use the OOXML libraries? – James Jan 19 '16 at 14:40
  • @JamesBarrass I tried with Open XML but couldn't get it to work due to finding image in the headers. I managed to do what I wanted manually, so I have tried to automate it. – PurpleSmurph Jan 19 '16 at 14:42
  • 1
    Solution in the dupe Q is correct, however to fix this with the above code - `ZipFile.CreateFromDirectory(extractpath, newDoc,CompressionLevel.Optimal, false);` - changing from true to false will stop a root folder being created above the necessary files. – PurpleSmurph Jan 19 '16 at 15:27

0 Answers0