【发布时间】:2016-07-30 18:01:18
【问题描述】:
我正在编写一个方法,该方法将进入一个目录,查找所有 doc 文件并替换其中的特定文本。因此,我的方法接受三个参数。
- 目录路径
- 我要替换的字符串
- 新的替换字符串
我面临的问题是当我点击受密码保护的文档时。在打开文档之前,我无法检查文档是否受到保护。在这种情况下,每次我检查文档时,我都会收到一个对话框字窗口询问密码。我想检查文档是否受到保护,如果它只是继续使用 foreach。
这是我的代码:
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);
}
}
【问题讨论】:
标签: c# .net ms-word office-interop