Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查docx文件中是否存在word_C#_Openxml Powertools - Fatal编程技术网

C# 检查docx文件中是否存在word

C# 检查docx文件中是否存在word,c#,openxml-powertools,C#,Openxml Powertools,我已将此docx文件加载到我的代码中: byte[] documentBytes = File.ReadAllBytes("C:\\mydocument.docx"); 本文档的正文、页眉或页脚中都包含“foo”一词,检查“foo”一词是否存在的最简单方法是什么 变量headerCount、footerCount和bodyCount表示文档每个部分的正则表达式点击数。MainDocumentPart属性还包含图像、图表、主题等的属性。由于不再维护链接中的repo,您可能希望

我已将此docx文件加载到我的代码中:

byte[] documentBytes = File.ReadAllBytes("C:\\mydocument.docx");
本文档的正文、页眉或页脚中都包含“foo”一词,检查“foo”一词是否存在的最简单方法是什么


变量
headerCount
footerCount
bodyCount
表示文档每个部分的正则表达式点击数。
MainDocumentPart
属性还包含图像、图表、主题等的属性。

由于不再维护链接中的repo,您可能希望更新存储库链接。请参考这个更新的好观点。我在下面贴了我自己的答案,这就是为什么这是一个非常稀疏的问题。虽然如此强烈地鼓励用户自己回答他们的问题,但这并不意味着这个问题可能缺少任何相关信息。发布问题的规则就像你没有回答你的问题一样,所以请在你的问题中提供每一个相关的信息。我总是想改进我自己的问题。在这种情况下,你能给我一个建议吗?在这种情况下,发布代码似乎有点无用。实际上,您可以提供您的尝试以及它们是如何失败的。这是个问题,记得吗?因此,它不需要包含答案。如果我没记错的话,你昨天的问题已经给出了一些建议。我之前的问题中也没有代码。但是我会在这个问题上添加一些额外的代码,这样看起来就很别致了。
using OpenXmlPowerTools;

...

byte[] documentBytes = GetMyBytes(); // Load the docx file with File.ReadAllBytes, generate a byte array, etc
using var myStream = new MemoryStream(result, false);
using var myDocument = WordprocessingDocument.Open(myStream, false); // myStream can also be replaced with a path in string format

var regex = new Regex("foo");

int headerCount = OpenXmlRegex.Match(document.MainDocumentPart.HeaderParts.SelectMany(x => x.GetXDocument().Descendants(W.p)), regex);
int footerCount = OpenXmlRegex.Match(document.MainDocumentPart.FooterParts.SelectMany(x => x.GetXDocument().Descendants(W.p)), regex);
int bodyCount = OpenXmlRegex.Match(document.MainDocumentPart.GetXDocument().Descendants(W.p), regex);