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;
}