C# 如何用C语言搜索word文件中的给定单词#

C# 如何用C语言搜索word文件中的给定单词#,c#,.net,aspose,C#,.net,Aspose,如何检查word文件是否包含给定的单词 例如: 我想写一个函数:booliscontain(stringword,stringfilepath)。 如果filePath包含word,则函数将返回true。否则它将返回false 这是我使用Aspose框架的解决方案。有没有更好的解决办法 public class FindContentOfWordDoc { public bool FindContent(string filePath, string content) {

如何检查word文件是否包含给定的单词

例如: 我想写一个函数:booliscontain(stringword,stringfilepath)。 如果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;
        }
    }
}

谢谢

如果您使用的是评论中所述的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;

}

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

我试过用一个框架词。有没有更好的解决方案?你是在说Microsoft Word吗?是的,我是在说MS Word。你是否尝试过将整个文件作为字符串读取并从中进行检查?AFAIR通常在word文档中不会对文本进行加密。不,我没有尝试过。它对WordMS不起作用。这是真的。很抱歉。我没有正确理解这个问题。我觉得这个片段很管用!