Highlight duplicate question in MS Word Document in C# Windows Form

Last Reply on Aug 15, 2016 04:35 AM By dharmendr

Posted on Aug 15, 2016 02:14 AM

Hi! How I can convert Highlight duplicate question in MS Word Document in C# to C#? It's write in web application. I want write in windows application.

You are viewing reply posted by: dharmendr on Aug 15, 2016 04:35 AM.
Posted on Aug 15, 2016 04:35 AM Modified on one year ago

Hi PRA,

Refer the below code.

private void btnUpload_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        Document doc = new Document();
        string filePath = openFileDialog1.FileName;//Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("bin")) + "Files\\Test.doc";
        object missing = System.Type.Missing;
        object fileName = filePath;
        doc = word.Documents.Open(ref fileName,
                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);
        List<string> data = new List<string>();
        for (int i = 0; i < doc.Paragraphs.Count; i++)
        {
            string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
            if (temp != string.Empty)
                data.Add(temp);
        }
        var duplicateQuestions = data.Where(x => x.Contains("@")).Select(y => y.Split('.')[1].Trim()).GroupBy(x => x).Where(z => z.Count() > 1).Select(k => k.Key);
        foreach (string item in duplicateQuestions)
        {
            int count = 0;
            for (int i = 0; i < doc.Paragraphs.Count; i++)
            {
                string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
                if (temp.Split('.').Length > 1)
                {
                    if (item == temp.Split('.')[1].Trim())
                    {
                        count++;
                    }
                    if (item == temp.Split('.')[1].Trim() && count > 1)
                    {
                        doc.Paragraphs[i + 1].Range.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed;
                    }
                }
            }
        }
        doc.Save();
        doc.Close(ref missing, ref missing, ref missing);
        ((_Application)word).Quit();
    }
}

Screenshot