Reputation: 2229
Below is my code, but the password is not removed. When I open the Word manually, the password dialog is still poping up.
I have tried the Unprotect method also, but that doesn't work also.
private static void WordUnProtect(string fileName, string password)
{
var app = new Word.Application();
Word.Document doc = null;
try
{
doc = app.Documents.Open(fileName, PasswordDocument: password);
// this doesn't work also
//doc.Unprotect();
doc.Password = string.Empty;
doc.Save();
}
finally
{
if (doc != null)
{
doc.Close(false);
Marshal.ReleaseComObject(doc);
}
if (app != null)
{
app.Quit();
Marshal.ReleaseComObject(app);
}
}
}
Upvotes: 2
Views: 1402
Reputation: 42494
It looks like that setting the Password
property doesn't actually mark the document as dirty so it will not be saved. I've skimmed over the documentation to see if there was an option to force it to Save anyway/make it dirty. That I couldn't find although I vaguely recall that such option existed in early versions of the Word Automation Model.
So I came up with this small hack to make a small change to the document but also removing that change at the same time.
// doc IsDirty
doc.Range(0, 0).InsertBefore(" ");
// no more password
doc.Password = null;
// let's remove what was Inserted
doc.Range(0, 1).Text ="";
The other option is of course doing a SaveAs
as suggested by MickyD but then you need to write to a temp file, close and release properly so the original file isn't locked anymore, delete the original and move the tempfile to the original. That will work, feels like it has more fail cases.
Upvotes: 3