0
私はすべてのdocファイルを見つけて内部の特定のテキストを置換するディレクトリに入る方法を書いています。このため、私のメソッドは3つの引数を受け取ります。内部でテキストを変更する前にワード文書がパスワードで保護されているかどうかを検出します
- ディレクトリパス
- 私はパスワードで保護された文書を打ったとき、私は直面しています問題がある
- 新しい置換文字列
を代用したい文字列。私はそれを開く前に文書が保護されているかどうかを確認することができません。この場合、私は文書をチェックするたびにパスワードを尋ねるダイアログワードウィンドウが表示されます。私は、文書が保護されているかどうかをチェックしたい。もし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);
}
}
これは良いアイデアです。私はそれを試しました。しかし、PasswordDocumentパラメータでは、文書のパスワードダイアログという単語を閉じることはありません。 –