简体   繁体   English

如何在 C# 的字节数组中找到一个字符串?

[英]How do I find a string in byte array in C#?

I have an array of bytes that contains data.我有一个包含数据的字节数组。 I would like to search for a specific string in the array of bytes.我想在字节数组中搜索特定的字符串。 I dont know really how to do this in C#我真的不知道如何在 C# 中做到这一点

byte[] ByteArray = File.ReadAllBytes(@"d:/MyDoc.docx");

String searchString = "Graphics";

How do I find the the word "Graphics" in the array dataArray?如何在数组 dataArray 中找到单词“Graphics”? Thanks谢谢

You can convert your array of bytes into string like here您可以像这里一样将字节数组转换为字符串

string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

and after that use the string.IndexOf() or string.Contains() method然后使用string.IndexOf()string.Contains()方法

Docx files are zipped . Docx 文件被压缩 The only strings you'll find there are relative to zip headers.您会找到的唯一字符串与 zip 标头相关。 There won't be any text from your document.您的文档中不会有任何文本。

You can see this in Windows by changing the docx file extension to zip and then double-clicking the file.您可以通过将docx文件扩展名更改为zip然后双击该文件,在 Windows 中看到这一点。 You'll find an archive with some XML content, which can open with any Xml reader, or even notepad.您会找到包含一些XML内容的存档,可以使用任何 Xml 阅读器甚至记事本打开。

You could do the same thing manually in code (ie via System.IO.Compression types), but you don't have to.您可以在代码中手动执行相同的操作(即通过System.IO.Compression类型),但您不必这样做。 There are other libraries that have already done much of the hard work for you to extract the archive and already know what files and schema to look for.还有其他库已经为您完成了许多艰苦的工作来提取档案,并且已经知道要查找哪些文件和架构。 Some of them freely available on NuGet.其中一些在 NuGet 上免费提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM