I have a script that copies a .docx template, copies it to a different location with a unique name, modifies it, then saves it. Occassionally, on the save, I get an file permission error. It’s weird because I will be using the same inputs and sometimes the error will show up and other times it won’t. Here’s my code:
File.Copy(Utilities.GetTemplateFilePath(), outputPath);
object path = outputPath;
object readOnly = false;
object o = System.Reflection.Missing.Value;
var document = word.Documents.Open(ref path, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
PopulateField(document.Paragraphs, 19, "aValue");
while (true) {
try {
document.Save();
break;
}
catch {
System.Threading.Thread.Sleep(100);
}
}
var documentClose = (Microsoft.Office.Interop.Word._Document)document;
documentClose.Close();
Another important hint is that when this problem occurs, there are .tmp files that are hanging around in the directory I’m writing to. Any idea what is going on here?
Error: Word cannot complete the save due to a file permission error.
(C:…\Document.docx)
You are hanging because you are not disposing of the COMInterop Object
try adding this code after you do the document.Close()