突出显示文本忽略 C# 中 Word 文档中的大小写

本文关键字:Word 文档 大小写 显示 文本 | 更新日期: 2023-09-27 18:36:27

使用以下代码,我能够突出显示搜索文本。但是,如果搜索文本是"也",则"也"不会突出显示。如何忽略案例。

 foreach (Word.Range w in doc.Words)
                            {
                                for (int i = 1; i < xmlnode.Count; i++)
                                {
                                    XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
                                    object text = xmlnode[i].FirstChild.InnerText;
                                    if (w.Text.Trim() == text.ToString())
                                    {
                                        w.Font.Bold = 1;
                                        w.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                                    }
                                }
                            }
                        }

突出显示文本忽略 C# 中 Word 文档中的大小写

       // int counter = 0;
        object readOnly = true;
        System.IO.StreamReader file =
         new System.IO.StreamReader(@"C:'Users'noor'Desktop'HIGH LIGHTER'Sample.txt");
        object matchWholeWord = true;
        //string textToFind  = "to";
        //string my = System.IO.File.ReadAllText(@"C:'Users'noor'Desktop'HIGH LIGHTER'Sample.txt");
        //var textToFind = my ;
       // textBox1.Text = textToFind.ToString ();
        while ((line = file.ReadLine()) != null)
        {
            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;
            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);
            string ReadValue = string.Empty;
            // Activate the document
            doc.Activate();
            /* foreach (Word.Range tmpRange in doc.StoryRanges)
             {
                 ReadValue += tmpRange.Text;
             }
         */
            foreach (Word.Range docRange in doc.Words)
                try
                {
                    if (docRange.Text.Trim().Equals(line, StringComparison.CurrentCulture) == false )
                    {
                        docRange.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                        docRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                }
        }
           // counter++;

        file.Close();
    }

您可能可以使用字符串 Compare 方法:

if(String.Compare(w.Text.Trim(), text.ToString(), true) == 0)