Check character exists in Word Document using C# and VB.Net in Windows Application

Last Reply 5 months ago By pandeyism

Posted 5 months ago

Hi! I want check between two sign . I have sentence want check exist or not one of this . or : or?.

for example:

@1. Where you from ? $

I want check exist . after number and ? before $

Posted 5 months ago Modified on 5 months ago

Hey PRA,

Please refer below sample.

Namespaces

C#

using Microsoft.Office.Interop.Word;

VB.Net

Imports Microsoft.Office.Interop.Word

Code

C#

public Form1()
{
    InitializeComponent();
    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
    Document doc = new Document();
    string filePath = "Test.docx";
    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.Contains(".") || temp.Contains(":") || temp.Contains("?"))
        {
            data.Add(temp);
        }
    }
    ((_Application)word).Quit();
}

VB.Net

Public Sub New()
    InitializeComponent()
    Dim word As Application = New Application()
    Dim doc As Document = New Document()
    Dim filePath As String = "Test.docx"
    Dim missing As Object = System.Type.Missing
    Dim fileName As Object = filePath
    doc = word.Documents.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
    Dim data As List(Of String) = New List(Of String)()

    For i As Integer = 0 To doc.Paragraphs.Count - 1
        Dim temp As String = doc.Paragraphs(i + 1).Range.Text.Trim()

        If temp.Contains(".") OrElse temp.Contains(":") OrElse temp.Contains("?") Then
            data.Add(temp)
        End If
    Next

    CType(word, _Application).Quit()
End Sub