C#使用COM搜索本地word文档关键字

        /// <summary>
/// 检索根目录下的子目录及其所有文件,并在datagridview中显示文档名称及路径--递归调用
/// </summary>
/// <param name="rootPath">根目录</param>
/// <param name="strKey">关键字包</param>
private void GetAllFiles(string rootPath,List<string> strKey)
{
DirectoryInfo dir = new DirectoryInfo(rootPath);
string[] dirs = System.IO.Directory.GetDirectories(rootPath);//得到所有子目录
foreach (string di in dirs)
{
GetAllFiles(di,strKey);
}
FileInfo[] files = dir.GetFiles("*.doc"); //查找文件
//遍历每个word文档
foreach (FileInfo fi in files)
{
string filename = fi.Name;
string filePath = fi.FullName;
object filepath = filePath;
filename = SearchDoc.SearchInDoc(filepath, strKey, filename); //调用检索文档关键字的方法,并返回检索出的文档名称
if (filename != "")
{
dtBGMC.Rows.Add(filename, filepath); //datagridview逐行显示检索出来的结果
}
}
} /// <summary>
/// search in a DOC file(查询DOC文件的内容)
/// </summary>
/// <param name="filepath">文档路径</param>
/// <param name="strKey">要搜索的关键字数组</param>
/// <param name="filename">文档名称</param>
/// <returns></returns>
public static string SearchInDoc(object filepath, List<string> strKey, string filename)
{
string KeyInfilename = "";
object MissingValue = System.Reflection.Missing.Value;//Type.Missing;
try
{
wp = new Microsoft.Office.Interop.Word.ApplicationClass();
wd = wp.Documents.Open(ref filepath, ref MissingValue,
ref readOnly, ref MissingValue,
ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue);
Microsoft.Office.Interop.Word.Find wfnd; if (wd.Paragraphs != null && wd.Paragraphs.Count > )
{
int keyscount = ;
for (int i = ; i < strKey.Count; i++) //循环关键字数组
{
for (int j = ; j <= wd.Paragraphs.Count; j++)
{
wfnd = wd.Paragraphs[j].Range.Find;
wfnd.ClearFormatting();
wfnd.Text = strKey[i].ToString();
if (wfnd.Execute(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
ref MissingValue, ref MissingValue, ref MissingValue))
{
keyscount++;
break;
}
}
}
if (keyscount == strKey.Count)
{
KeyInfilename = filename;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (wd != null)
{
wd.Close(ref MissingValue, ref MissingValue, ref MissingValue);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
wd = null;
} if (wp != null)
{
wp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
wp = null;
} GC.Collect();
}
return KeyInfilename;
}
}
}
上一篇:聊聊Azure的安全性


下一篇:RESTful URL设计指南(转)