Sunday, January 22, 2023

VB.NET Read/Parse text file and Insert Data into SQL Server Table

VB.NET Read text file and Insert Data into SQL Server Table

Dim FILE_NAME As String = "c:/test/FileToUpload_20230102.013721.txt"

        Dim TextLine As String
        If System.IO.File.Exists(FILE_NAME) = True Then
            Dim objReader As New System.IO.StreamReader(FILE_NAME)
            Dim Str1
            Dim Str2
            Dim Str3
            Dim Str4
            Dim lineCount As Integer 'lines read so far in file
            Do While objReader.Peek() <> -1
                '                TextLine =   objReader.ReadLine() 
                TextLine = objReader.ReadLine()
                Str1 = TextLine.Substring(0, 2)
                If Str1 = "DE" Then
                    Str2 = TextLine.Substring(3, 1)
                    Str3 = TextLine.Substring(4, 3)
                    Str4 = TextLine.Substring(5, 10)

                    ' insert data into sql table
                    Dim query As String = "INSERT INTO  DBO.LoaddataPharmacy_Pal([RECORD TYPE],[RECORD INDICATOR],[ELIGIBLE COVERAGE CODE],[USER BENEFIT ID]) "
                    query = query & " VALUES ('" & Str1 & "' , '" & Str2 & "','" & Str3 & "','" & Str4 & "')"

                    Dim cmd As SqlCommand = New SqlCommand(query, _cn)
                    'cmd.Parameters.AddWithValue("@ROLEID", txtroleId.Text)

                    _cn.Open()
                    cmd.ExecuteNonQuery()
                    _cn.Close()
                End If
                Str1 = ""
                lineCount = lineCount + 1 'increment lineCount
           Loop
            ' Textbox1.Text = TextLine
        Else
            MessageBox.Show("File Does Not Exist")
        End If

No comments: