如何通过C#在单词文件中搜索给定单词

时间:2018-08-10 03:26:55

标签: c# .net aspose

如何检查单词文件中是否包含给定单词?

示例:      我想编写一个函数:bool IsContain(string word,string filePath)。      如果 filePath 包含 word ,该函数将返回true。否则它将返回false。

这是我使用Aspose框架的解决方案。有更好的解决方案吗?

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;
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

使用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.");
}

答案 1 :(得分:0)

如果您按照注释中所述使用Aspose库,则可以通过IReplacingCallback接口的自定义实现来实现。

bool IsContain(string word, string filePath)
{
    Document doc = new Document(filePath);

    OccurrencesCounter counter = new OccurrencesCounter();

    doc.Range.Replace(new Regex(word), counter, false);

    return counter.Occurrences > 0;

}


private class OccurrencesCounter : IReplacingCallback
{
    public ReplaceAction Replacing(ReplacingArgs args)
    {
        mOccurrences++;

        return ReplaceAction.Skip;
    }


    public int Occurrences
    {
        get { return mOccurrences; }
    }

    private int mOccurrences;

}