Dani AI

Generated

Short expert note (builds on ): loading the file into a WinForms RichTextBox, locating each match, and applying a background color to that selection is the straightforward route. The snippet below shows a minimal, robust way to highlight whole-word matches (case-insensitive) and then save the control as an image if an image is needed.

using System.IO;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

void HighlightWordInFile(RichTextBox rtb, string filePath, string word)
{
    rtb.Text = File.ReadAllText(filePath);
    // whole-word match, case-insensitive
    string pattern = @"\b" + Regex.Escape(word) + @"\b";
    foreach (Match m in Regex.Matches(rtb.Text, pattern, RegexOptions.IgnoreCase))
    {
        rtb.Select(m.Index, m.Length);
        rtb.SelectionBackColor = Color.Yellow;
    }
    rtb.Select(0, 0); // clear caret without removing formatting
}

void SaveRichTextBoxAsImage(RichTextBox rtb, string imagePath)
{
    using (var bmp = new Bitmap(rtb.Width, rtb.Height))
    {
        rtb.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
        bmp.Save(imagePath, ImageFormat.Png);
    }
}

Notes and practical tips:

  • The regex uses \b to avoid highlighting substrings inside other words. Remove \b if substring matches are required.
  • SelectionBackColor applies formatting into the RTF, so highlights persist after changing selection. Calling rtb.Select(0,0) removes the caret but keeps the highlight. Setting rtb.HideSelection = false helps preserve visible selection when focus changes.
  • For very large files, iterating and applying selection formatting can be slow. If performance becomes an issue, consider building the RTF directly or using lower-level rendering (EM_FORMATRANGE) rather than per-match Select/SelectionBackColor changes.
  • DrawToBitmap captures the control as displayed; to render the entire document (not just the visible portion), ensure the control is sized to show all text or use a dedicated text-to-bitmap rendering approach.

This expands 's suggestion into a ready-to-use pattern and also includes a simple export-to-image step for the “highlighted text in image” case mentioned by .

Recommended Answers

All 3 Replies

How to find a word in a text file in c#? I need highlighted text in image h

How to find a word in a text file in c#? I need highlighted text in image ?

Load the text of your file in a RichTextBox.
Use a Find method of RichTextBox to find words.
Apply other style to the found words.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.