首页 > 解决方案 > How to search a given word in word file by C#

问题描述

How can I check that a word file is contain a given word or not?

Example: I want to write a function: bool IsContain(string word, string filePath). The function will return true if filePath is contain word. Otherwise it will return false.

This is my solution with Aspose framework. Is there any better solution?

public class FindContentOfWordDoc
{
    public bool FindContent(string filePath, string content)
    {
        var doc = new Document(filePath);

        var findReplaceOptions = new FindReplaceOptions
        {
            ReplacingCallback = new FindCallBack(),
            Direction = FindReplaceDirection.Backward
        };

        var regex = new Regex(content, RegexOptions.IgnoreCase);
        doc.Range.Replace(regex, "", findReplaceOptions);

        return (findReplaceOptions.ReplacingCallback as FindCallBack)?.IsMatch ?? false;
    }

    private class FindCallBack : IReplacingCallback
    {
        public bool IsMatch { get; private set; }
        ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
        {
            IsMatch = true;
            return ReplaceAction.Stop;
        }
    }
}

Thanks!

标签: c#.netaspose

解决方案


遵循使用 VSTO 的代码段:

if (Application.Selection.Find.Execute(ref findText,
ref missing, ref missing, ref missing, ref missing, ref missing, ref 
missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref 
missing, 
ref missing, ref missing)) 
{ 
   MessageBox.Show("Text found.");
} 
else
{ 
   MessageBox.Show("The text could not be located.");
}

推荐阅读