Reputation: 11
I am writing a method which will go into a directory find all doc files and substitute specific text inside. For this reason my methods accepts three arguments.
The issue I am facing is when i hit a document which is password protected. I am not able to check if the document is protected before i open it. In this case every time I check the document I get a dialog word windows asking password. I want to check the if the document is protected, if it is just continue with the foreach.
This is my code:
private static void ReplaceString(string folderPath, string findText, string replaceText)
{
// retrieve all doc files from the specified directory
var wordFiles = Directory.GetFiles(folderPath, "*.doc", SearchOption.AllDirectories);
var filtered = wordFiles.Where(f => !f.Contains('$'));
foreach (var wordFilePath in filtered)
{
Console.WriteLine(wordFilePath);
// start a new word application
FileInfo fi = new FileInfo(wordFilePath);
// var wordDocument = new Document();
//checking the current element if: is in use, is readonly, if is protected by password
if (IsLocked(fi))
{
continue;
}
var wordApplication = new Application { Visible = false };
//opening the word document
Document wordDocument = null;
// I want to catch here if the document is protected just to contonie forward
try
{
wordDocument = wordApplication.Documents.Open(wordFilePath, ReadOnly: false, ConfirmConversions: false);
}
catch (COMException e)
{
continue;
}
//Unfolding all fields in a document using ALT + F9
wordDocument.ActiveWindow.View.ShowFieldCodes = true;
// using range class to populate a list of all document members
var range = wordDocument.Range();
try
{
range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);
}
catch (COMException e)
{
continue;
}
// replace searched text
var shapes = wordDocument.Shapes;
foreach (Shape shape in shapes)
{
var initialText = shape.TextFrame.TextRange.Text;
var resultingText = initialText.Replace(findText, replaceText);
shape.TextFrame.TextRange.Text = resultingText;
}
// Show original fields without code
wordDocument.ActiveWindow.View.ShowFieldCodes = false;
// save and close the current document
wordDocument.Save();
wordDocument.Close();
wordApplication.NormalTemplate.Saved = true;
wordApplication.Quit();
// Release this document from memory.
Marshal.ReleaseComObject(wordApplication);
}
}
Upvotes: 0
Views: 1193
Reputation: 209
The Documents.Open() method has a PasswordDocument
parameter. if you assign it to a random password (wrong password), the method will just ignore the password you assigned if the document is not password protected. If the document is password protected, the method will throw 5408 exception, which you can catch.
Upvotes: 3