I wrote a program that search for a specific text in a word document, but my problem is that when it opens a read only file it shows a dialog message that says 'File xx is reserved by xx. Enter password for write access'. How can i prevent this message from showing ? I would like to skip this kind of files if i come across them. Can i maybe use OpenXml() or Stream to detect these kind of files ?
The try catch it's able to catch documents protected by password, but it can't catch readonly(password protected) documents. It opens the password dialog instead.
Here is my code below :
public List<string> FindTexInWordDoc(string searchFor, string filePath)
{
List<string> foundMatches = new List<string>();
Microsoft.Office.Interop.Word.Application app = null;
Microsoft.Office.Interop.Word.Document doc = null;
try
{
app = new Microsoft.Office.Interop.Word.Application();
object objPass = "1111111111111";
object missing = System.Type.Missing;
object ReadOnly = false;
object visible = false;
app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
doc = app.Documents.Open(filePath, ref missing, ref ReadOnly, ref missing, ref objPass, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
string[] allWords = doc.Content.Text.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
for (int x = 0; x < allWords.Length; x++)
{
if (allWords[x].ToLower().Contains(searchFor.ToLower()) == true)
foundMatches.Add(allWords[x]);
if (started == false)
break;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (doc != null)
{
doc.Close();
Marshal.FinalReleaseComObject(doc);
}
if (app != null)
{
app.Quit();
Marshal.FinalReleaseComObject(app);
}
}
return foundMatches;
}