Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to search a string from word document(.doc or .docx) in C#. I have converted that document in byte array. But unable to search.

C#
//Convert doc file in byte array
string filePath = "C:\\SearchFiles\\Doc1.doc";
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader reader = new BinaryReader(stream);
byte[] file = reader.ReadBytes((int)stream.Length);


I want to search a string(example : "transaction") in that document.


How can I search?

Please help.

Thanks in advance.

[Modified: added pre tags]
Posted
Updated 2-Apr-10 12:00pm
v2

I'm sure you could do it that way, but Microsoft has provided the object model for Word that you can use. Look up Microsoft.Office.Interop.Word.

The Microsoft Reference can be found at: Microsoft.Office.Interop.Word Namespace [^]

You can parse the document a lot easier with those classes.
 
Share this answer
 
Thank you.
Now I have done this. I have added Microsoft Word 11.0 Object Library in my application.
<pre lang="cs">
object path = Path.GetFullPath(filePath);
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
object missing = System.Type.Missing;

doc = word.Documents.Open(ref path, 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, ref missing);
doc.Activate();
foreach (Word.Range tmpRange in doc.StoryRanges)
{
tmpRange.Find.Text = searchString;
tmpRange.Find.Wrap = Word.WdFindWrap.wdFindStop;
bool find = tmpRange.Find.Execute(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, ref missing);
if (find == true)
{
fileName = fileName + Path.GetFileName(filePath).ToString() + ";";
}
}
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);

Now the below code is working.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900