Search code examples
c#.netwinformsms-wordoffice-interop

Deleting a specific line in an MS Word document


I have been trying to delete a specific line from a word doc. The logic is , if I find a particular word in the document, I need to delete that particular line which contains the word. Do far I have only written the logic to find the word. However, tracing the line number ad deleting the line, I am unable to do. searched a lot I multiple websites, however, I am very puzzled now. Could you please help me out on this ?

below is my code:-

 void searchText(string txt)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\testdoc1.docx");
            object missing = System.Reflection.Missing.Value;
            doc.Content.Find.ClearFormatting();
            object keyword = txt.ToString();
            if (doc.Content.Find.Execute(ref keyword, 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))
            {
                //Need the logic to delete the line here
            }
            else
            {
                MessageBox.Show("Not found");
            }
            doc.Close(ref missing, ref missing, ref missing);
            app.Quit(ref missing, ref missing, ref missing);            
        }

Please let me know if you need any other information.

NOTE: The search keyword is given by a textbox and the above function is called from a button.


Solution

  • Something like

    var range = doc.Content;
    if (range.Find.Execute(txt))
    {
        range.Expand(WdUnits.wdLine); // or change to .wdSentence or .wdParagraph
        range.Delete();
    }