Remove blank lines at the end of a file - vb.net

I am trying to remove the blank lines at the end of a text file. The program takes a file, manipulates it and produces another file. However, there's blank lines at the end of the file that I need to get rid of...
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' Save to desktop if nothing is selected
If txtDestLoc.Text = "" Then
txtDestLoc.Text = "C:\Documents and Settings\" & LCase(Environment.UserName) & "\desktop"
End If
If txtFileLoc.Text <> "" Then
Dim fsr As New FileStream(txtFileLoc.Text, FileMode.Open)
Dim sr As New StreamReader(fsr)
Dim sb As New System.Text.StringBuilder
'Dim strHeader As String
' Get just file name
Dim strFileName = Me.OpenFileDialog1.FileName()
Dim fnPeices() As String = strFileName.Split("\")
Dim fileName As String = ""
fileName = "CCCPositivePay.txt"
Dim strOutFile As String = txtDestLoc.Text & "\" & fileName
Dim fsw As New FileStream(strOutFile, FileMode.Create, FileAccess.Write)
Dim w As New StreamWriter(fsw)
Dim i As Double
Dim srRow As String
Dim strW As String
Dim strDate As String
Dim strAmt As String
Dim strChNo As String
Dim strName As String
Dim strAddInfo As String
Dim strCustAcct As String
Dim totamt As Double = 0
Dim strAcct As String = "2000002297330"
strLoc = txtDestLoc.Text()
srRow = ""
Do While sr.Peek() <> -1
srRow = srRow.ToString & sr.ReadLine()
If srRow.Length = 133 Then
If srRow.Substring(131, 2) = "CR" Then
strCustAcct = srRow.Substring(2, 18).Replace("-", "")
strName = srRow.Substring(23, 35)
strAddInfo = srRow.Substring(23, 30)
strDate = srRow.Substring(103, 4) + srRow.Substring(97, 2) + srRow.Substring(100, 2)
strChNo = srRow.Substring(110, 10)
strAmt = strip(srRow.Substring(121, 10))
strW = strAcct + strChNo.Trim.PadLeft(10, "0") + strAmt.Trim.PadLeft(10, "0") + strDate + " " + strAddInfo + Space(8) + strName + Space(20)
sb.AppendLine(strW)
totamt = totamt + CDbl(strAmt)
i = i + 1
End If
End If
srRow = ("")
Loop
'w.WriteLine(strHeader)
w.WriteLine(sb.ToString)
Dim file As String = txtFileLoc.Text
Dim path As String = txtFileLoc.Text.Substring(0, File.lastindexof("\"))
Dim strFileProcessed As String
strFileProcessed = fnPeices(fnPeices.Length - 1)
Label1.Text = "Refund File Processed: " & strFileProcessed
Label2.Text = "File saved to: " & strOutFile
' Close everything
w.Close()
sr.Close()
fsw.Close()
fsr.Close()
' Move file after processing
System.IO.File.Move(file, path + "\CB008_Processed\" + Now.ToString("MMddyyyyHHmm") + strFileProcessed)
' Put a copy of the results in "Processed" folder
System.IO.File.Copy(strOutFile, path + "\CB008_Processed\" + Now.ToString("MMddyyyyHHmm") + fileName)
Else
MessageBox.Show("Please select a Refund file to process.", "CCC Refund File", MessageBoxButtons.OK)
End If
End Sub
Public Function strip(ByVal des As String)
Dim strorigFileName As String
Dim intCounter As Integer
Dim arrSpecialChar() As String = {".", ",", "<", ">", ":", "?", """", "/", "{", "[", "}", "]", "`", "~", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "|", " ", "\"}
strorigFileName = des
intCounter = 0
Dim i As Integer
For i = 0 To arrSpecialChar.Length - 1
Do Until intCounter = 29
des = Replace(strorigFileName, arrSpecialChar(i), "")
intCounter = intCounter + 1
strorigFileName = des
Loop
intCounter = 0
Next
Return strorigFileName
End Function

Only do a Writeline if Not String.IsNullOrEmpty(sb)

Related

Visual Basic write text file adds an extra line feed

I have a visual basic application where I read in an excel spreadsheet and write the contents to a .csv file. The application works as expected however there appears to be an extra line feed generated at the end of each line. This is the code I am executing:
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Visible = True
Dim fileName As String = OpenFileDialog1.FileName.ToString()
Dim sPath As String = StrReverse(fileName) 'reverse the string
sPath = Mid(sPath, InStr(sPath, "\"), Len(sPath)) 'extract from the first slash
sPath = StrReverse(sPath) 'reverse it again
Dim xlsFileFolder As String = sPath
Dim xlsFileName As String = Path.GetFileName(fileName)
Dim csvFileName As String = Path.GetFileNameWithoutExtension(fileName) + ".csv"
Dim csfFileNameAndPath As String = xlsFileFolder + csvFileName
If Not (strm Is Nothing) Then
Dim di As New IO.DirectoryInfo(xlsFileFolder)
Dim aryFi As IO.FileInfo() = di.GetFiles(xlsFileName)
Dim ds As New DataSet
Dim workbook As IWorkbook
Dim worksheet As ISheet
Dim sheetCount As Integer
Dim file = New FileStream(fileName, FileMode.Open, FileAccess.Read)
workbook = New HSSFWorkbook(file)
sheetCount = workbook.NumberOfSheets
Dim table As New DataTable
worksheet = workbook.GetSheetAt(0)
Dim numberOfDataRecords = worksheet.PhysicalNumberOfRows
Dim numberOfColumns = worksheet.GetRow(0).PhysicalNumberOfCells
Dim dataRow As Integer = 0
Dim dataColumn As Integer = 0
Dim quote As String = """"
Dim cellData As String = ""
Using writer As StreamWriter = New StreamWriter(csfFileNameAndPath)
For dataRow = 0 To numberOfDataRecords - 1
Dim csvLine As String = quote
For dataColumn = 0 To numberOfColumns - 1
cellData = worksheet.GetRow(dataRow).GetCell(dataColumn).ToString()
cellData = cellData.Replace(quote, "'")
csvLine = csvLine + cellData + quote + "," + quote
Next
Dim l As Integer = csvLine.Length - 2
csvLine = Microsoft.VisualBasic.Left(csvLine, l)
csvLine = csvLine + vbCr
writer.WriteLine(csvLine)
Next
End Using
TextBox1.Text = "Done!"
End If
End Sub
This is an image of the selected excel file:
And this is an image of the resulting .csv file:
As you can see, there is a blank line being generated after each line of text in the .csv file.
Any assistance is greatly appreciated.
Thanks!
Remove this line and you should be fine. csvLine = csvLine + vbCr

Message Buffer for TCP Listener

I have a TCP Listener in a vb.net class that listens for data that another program sends out. The problem is it sends the data at a faster rate than my processing routine can process it. The routine will be about half way thru processing the last message and here comes another message on the listening port and it starts the processing without finishing the other message.
I want to add a message buffer so all incoming text strings are placed in a stack and when my processing routine gets done it will pull the next string out of the stack and work with it and then pull the next one until the stack is empty
I'm not sure of the best way to do this. I'm looking to see what someone thinks would be the best way to handle this.
TIA
Rick
Private Sub TCPListening()
Dim CommandString As String = ""
Dim ParamLength As Short
Dim ADIFStr As String = ""
Dim tmpStr As String = ""
Dim tmpBool As Boolean
Dim paramStr As String = ""
Dim xcvrfreq As String = ""
Dim xcvrmode As String = ""
Dim prsvsplit As String = ""
Dim Arr() As String
Dim decimalstr As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Dim thousandsstr As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
If ExternalTcpListener Is Nothing Then
ExternalTcpListener = New TcpListener(IPAddress.Parse(ExternalTCPIP), ExternalTCPPort)
ExternalTcpListener.Start()
End If
Try
Dim responseString As String = ""
Dim sendBytes As [Byte]()
Dim ExternaltcpClient As TcpClient = ExternalTcpListener.AcceptTcpClient()
While True
Debug.Print("Start While")
Dim networkStream As NetworkStream = ExternaltcpClient.GetStream()
Dim bytes(ExternaltcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(ExternaltcpClient.ReceiveBufferSize))
Dim Sentdata As String = System.Text.Encoding.ASCII.GetString(bytes)
ttimer.start()
Sentdata = Replace(Sentdata, vbNullChar, "")
If Sentdata <> "" Then Debug.Print("SendData= " & Sentdata)
If InStrRev(Sentdata, "<command:") > 8 Then
'<command:10>CmdSetFreq<parameters:23><xcvrfreq:10> 7,185.000<command:10>CmdGetFreq<parameters:0>
'If multiple commands are recieved this section of the routine splits them up and processes each one as seperate commands.
Sentdata = Strings.Replace(Sentdata, "<command", "|<command")
Arr = Split(Sentdata, "|")
Debug.Print(" Arr=" & UBound(Arr))
For x = 1 To UBound(Arr)
Sentdata = Arr(x)
Debug.Print(" New " & Sentdata)
If InStr(Sentdata, "<command") Then
tmpStr = Sentdata
tmpStr = Right(Sentdata, Len(Sentdata) - 1)
CommandString = Extract(tmpStr, ">", "<")
ParamLength = Extract(Sentdata, "<parameters:", ">")
Select Case CommandString
Case "CmdSetFreqMode", "CmdQSXSplit", "CmdSetFreq", "CmdSetTXFreq", "CmdSetMode", "CmdSplit" ', "CmdTX", "CmdRX"
Station.ActiveWindow.SetExternalTCPCommandsInvoke(Sentdata)
'The above commands are processed and handled in EntryWindow.SetExternalTCPCommands
Case "CmdGetFreq"
'<command:10>CmdGetFreq<parameters:0>
Debug.Print("NI1Inside: " & CommandString & " " & Sentdata)
If ParamLength = 0 Then
tmpStr = Format(Val(Station.ActiveRadio.Frequency), "##,###.000")
responseString = "<CmdFreq:" & Len(tmpStr) & ">" & tmpStr
Debug.Print("[R1] " & responseString)
sendBytes = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
'LogError("CmdGetFreq1Response - ElapsedTime: " & ttimer.ElapsedMilliseconds)
End If
Case "CmdGetTXFreq"
'<command:12>CmdGetTXFreq<parameters:0>
Debug.Print("NIInside: " & CommandString & " " & Sentdata)
If ParamLength = 0 Then
tmpStr = Format(Val(Station.ActiveRadio.TXFreq), "##,###.000")
If Len(tmpStr) = 0 Then
responseString = "<CmdTXFreq:4>.000"
Else
responseString = "<CmdTXFreq:" & Len(tmpStr) & ">" & tmpStr
End If
Debug.Print("[R1] " & responseString)
sendBytes = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
'LogError("CmdGetTXFreq1Response - ElapsedTime: " & ttimer.ElapsedMilliseconds)
End If
end select
End If
Next
'End If
ElseIf InStr(Sentdata, "command") And InStrRev(Sentdata, "<command:") < 8 Then
'This section of the routine processes single commands that are sent via the Listener
tmpStr = Sentdata
tmpStr= Right(Sentdata, Len(Sentdata) - 1)
CommandString = Extract(tmpStr, ">", "<")
ParamLength = Extract(Sentdata, "parameters:", ">")
Select Case CommandString
Case "CmdSetFreqMode", "CmdQSXSplit", "CmdSetFreq", "CmdSetTXFreq", "CmdSetMode", "CmdSplit" ', "CmdTX", "CmdRX"
Station.ActiveWindow.SetExternalTCPCommandsInvoke(Sentdata)
'The above commands are processed and handled in EntryWindow.SetExternalTCPCommands
Case "CmdGetFreq"
'<command:10>CmdGetFreq<parameters:0>
Debug.Print("NI2Inside: " & CommandString & " " & Sentdata)
If ParamLength = 0 Then
tmpStr = Format(Val(Station.ActiveRadio.Frequency), "##,###.000")
responseString = "<CmdFreq:" & Len(tmpStr) & ">" & tmpStr
Debug.Print("[R] " & responseString)
sendBytes = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
'LogError("CmdGetFreqResponse - ElapsedTime: " & ttimer.ElapsedMilliseconds)
End If
Case "CmdGetTXFreq"
'<command:12>CmdGetTXFreq<parameters:0>
Debug.Print("NI2Inside: " & CommandString & " " & Sentdata)
If ParamLength = 0 Then
tmpStr = Format(Val(Station.ActiveRadio.TXFreq), "##,###.000")
If Len(tmpStr) = 0 Then
responseString = "<CmdTXFreq:4>.000"
Else
responseString = "<CmdTXFreq:" & Len(tmpStr) & ">" & tmpStr
End If
Debug.Print("[R] " & responseString)
sendBytes = Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
'LogError("CmdGetTXFreqResponse - ElapsedTime: " & ttimer.ElapsedMilliseconds)
End If
There is alot of code missing but it gives you the general idea of what is happening.

VB2008 Changing string in a file

I want to change something on a compiled game file, so I used this code:
Private Sub Next2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Next2.Click
Dim reader As New System.IO.StreamReader("Languages/" & Language & ".Devil")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Tips.Text = ReadLine(6, allLines)
WeaponsListBox.Hide()
NewWeaponsList.Hide()
Next2.Hide()
Dim curItem As String = WeaponsListBox.SelectedItem.ToString()
Dim curItem2 As String = NewWeaponsList.SelectedItem.ToString()
Try
If MainWeapon = "Cheytac" Then
Dim supahotfire As String = curItem.Substring(0, 12)
Dim hotdestroyer As String = curItem.Replace(supahotfire, "")
Dim supa2 As String = curItem2.Substring(0, 12)
Dim hot2 As String = curItem2.Replace(supa2, "")
Dim oldfile As String = "pack/Weapon_" & curItem & ".i3pack"
Dim FileName As String = "pack/pack_" & MainWeapon & hot2 & "_" & hotdestroyer & ".i3pack"
Dim be = My.Computer.FileSystem.ReadAllBytes(oldfile)
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Dim be3 As String = be2.Replace("Weapon\" & curItem & "/Cheytac_M200_Diff.i3i", "Weapon\" & curItem2 & "/Cheytac_M200_Diff.i3i")
Dim be4 = UnicodeStringToBytes(be3)
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
'System.IO.File.AppendAllText(FileName, be4)
' Dim fs As FileStream = New FileStream(oldfile, FileMode.Open)
' Dim br As BinaryReader = New BinaryReader(fs)
'Dim bin as byte[]= br.ReadBytes(Convert.ToInt32(fs.Length));
' fs.Close()
'br.Close()
End If
Catch ex As Exception
System.IO.File.AppendAllText("MathimaticalErrors.txt", ex.ToString)
End Try
End Sub
Public Function UnicodeBytesToString(ByVal bytes() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
Public Function UnicodeStringToBytes(ByVal str As String) As Byte()
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
The problem is that the newly created file is basically the same as the old file, and nothing has changed on it. How can I solve this?
At this point in your code:
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
The value in be2 would remain unchanged. You have to store the return value of Replace():
Dim be2 As String = UnicodeBytesToString(be)
be2 = be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Also, at this line:
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
The True at the end means you want to append the bytes. If the file is empty this will be fine. If not, then you'll end up adding the bytes to the end of the file each time. Not sure if that is your intended result...

Automate PDF to Text VB.net

I'm currently using the below code in a VB.Net console app that takes the contents of a text file and extracts certain info and then exports it to a CSV.
All seems to work well but the problem is the file originally comes through as a PDF (only option possible) and i have to manually open the file in Adobe and 'Save as Text'.
Is there a way of either automating the conversion of PDF to text file or reading the PDF in place of the text file.
Any guidance or options would be appreciated
Dim iLine, iEnd, c, iField As Integer
Dim iSecs, iMax As Long
Dim sText, sTemp, sSchema As String
Dim sHotel, sEndDate, sMon, sPLU, sTots, sValue, sDept, sFile, sOutFile, sDesc As String
Dim tdate As Date
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\temp\TX.accdb;")
Dim LUse As Boolean
sHotel = "Unknown Hotel"
sEndDate = "01/01/2015"
sMon = "MAR"
sPLU = ""
sTots = "0"
sValue = "0"
sDept = "Unknown Dept"
sDesc = ""
LUse = True
sTemp = ""
iField = 0
sSchema = "Chester"
'Open input file
sFile = "c:\temp\input.txt"
Dim InFile As New System.IO.StreamReader(sFile)
'Open lookup data table
con.Open()
Dim dbAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
"SELECT * FROM Plookup", con)
Dim dsTX As DataSet = New DataSet()
Dim changes As DataTable
Dim cmdbuilder As OleDbCommandBuilder = New OleDbCommandBuilder(dbAdapter)
dbAdapter.FillSchema(dsTX, SchemaType.Source, "Plookup")
dbAdapter.Fill(dsTX, "Plookup")
Dim rstx As DataTable = dsTX.Tables(0)
iMax = rstx.Rows.Count
Dim productrow() As Data.DataRow
'Open Output file
iSecs = Timer
sOutFile = "c:\temp\TX" & Format$(Now, "yymmdd") & Trim$(Str$(iSecs)) & ".csv"
FileCopy(sFile, "c:\temp\TX" & Format$(Now, "yymmdd") & Trim$(Str$(iSecs)) & ".txt")
Dim OutFile As New System.IO.StreamWriter(sOutFile)
'Write header
OutFile.WriteLine("outlet,dept,epos,tots sold,total price,date of sales")
iLine = 0
Do While InFile.Peek() <> -1
'Read in text
iLine = iLine + 1
sText = InFile.ReadLine
sText = sText.Replace(",", "")
If Len(sText) > 2 And Len(sText) < 9 Then
If Mid$(sText, 3, 1) = "-" Then ' Department Name
sText = sText & Space(9 - Len(sText))
End If
End If
'Process all rows except header row - read data into array
If Len(sText) > 8 Then
Select Case Left(sText, 7)
Case "Consoli" ' Ignore
Case "Quanti " ' Ignore
Case "Group b" ' Ignore - but next row is the Hotel Name
iLine = iLine + 1
sText = InFile.ReadLine
sText = sText.Replace(",", "")
sHotel = Trim$(Left(sText, 20)) 'The username follows so we may truncate the hotel name
Case "Date ra" ' End date
sEndDate = Mid$(sText, 29, 2) & "/" & Mid$(sText, 32, 2) & "/" & Mid$(sText, 35, 4)
tdate = CDate(sEndDate).AddDays(-1)
sEndDate = tdate.ToString("dd/MM/yyyy")
Case Else 'Possible Code
If Mid$(sText, 3, 1) = "-" Then ' Department Name
sDept = Trim(sText)
Else
If IsNumeric(Left(sText, 7)) Then 'Got a code
sPLU = Trim(Str(Val(Left(sText, 7))))
'We don't know where the description ends as it contains spaces
'So best way is to start at the end and work back...
iEnd = Len(sText)
iField = 0
For c = iEnd To 9 Step -1
If Not (Mid(sText, c, 1) = " ") Or iField > 10 Then
sTemp = Mid(sText, c, 1) & sTemp
Else
iField = iField + 1
If iField = 9 Then
sValue = sTemp
ElseIf iField = 11 Then
sTots = sTemp
End If
sTemp = ""
End If
Next
If iField = 10 Then
sTots = Trim(sTemp)
sDesc = ""
Else
sDesc = Trim$(sTemp)
End If
'lookup code
productrow = rstx.Select("FileID = 'Chester' and PLU = '" & sPLU & "'")
If productrow.Length = 0 Then ' product not found
iMax = iMax + 1
rstx.Rows.Add(sSchema, sPLU, sDesc, False)
LUse = True
Else
LUse = Not productrow(0)("Exclude")
End If
If (Val(sTots) + Val(sValue) > 0) And LUse Then ' We have a non-zero sale or value and it is not excluded
OutFile.WriteLine(sHotel & "," & sDept & "," & sPLU & "," & sTots & "," & sValue & "," & sEndDate)
End If
End If
End If
End Select
End If
Loop
'dbAdapter.Update(dsTX.Tables(0))
'Close input / output csv files
'rstx.Rows.Add("303030", "Another Test", False)
dbAdapter.UpdateCommand = cmdbuilder.GetUpdateCommand(True)
dbAdapter.InsertCommand = cmdbuilder.GetInsertCommand(True)
dbAdapter.DeleteCommand = cmdbuilder.GetDeleteCommand()
changes = rstx.GetChanges()
If changes IsNot Nothing Then dbAdapter.Update(changes)
InFile.Close()
OutFile.Close()
con.Close()
Try itextSharp. itextSharp is a .NET DLL with the help of which you can extract content from PDF. Click here for reference & sample code(although code is in c#, its just a reference to give you an idea).

Read a text file which contains SQL code to create tables in a database

I need code to read a .txt file which is in my project bin\debug directory that contains SQL code to create tables in a large number it size of 936kb
This following code only I'm using...
By using this it gives result like table created but it is not reading the file... there is nothing in the database
Public Function readTextFile(ByVal fileName As String) As String
Dim strContent As String()
Dim x As String = ""
Try
'fileName = "CSYSS802.txt"
If Not System.IO.File.Exists(fileName) Then
'o Until EOF()
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x = x + Str
Next
readTextFile = x
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
readTextFile = x
End Function
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), "GO")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "")
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
In the readTextFile function, it will only attempt to read the text from the text file if the file DOESN'T exist. If the text file exists then the function returns an empty string and if the text file doesn't exist, the function will throw a file not found exception.
Replace:
If Not System.IO.File.Exists(fileName) Then
with:
If System.IO.File.Exists(fileName) = True Then
You might also want to include an Else clause in case the file doesn't exist as it won't throw an error since you have handled it correctly.
If System.IO.File.Exists(fileName) = True Then
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x &= Str
Next
Return x
Else
MessageBox.Show("The file '" & fileName & "' does not exist.")
Return ""
End If
My Self I had Found The solution..I attache the Following Code...It now Creating All tables Properly..
Make sure that each Sql Commands in your Text File ends with go.. because i used "GO" Keyword to split the text...
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), " GO ")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "", sqlCon1)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
Public Function readTextFile(ByVal file As String) As String
Dim fso As New System.Object
Dim ts As Scripting.TextStream
Dim sLine As String
fso = CreateObject("Scripting.FileSystemObject")
ts = fso.openTextFile(file)
Do Until ts.AtEndOfStream
sLine = sLine & " " & ts.ReadLine
Loop
ts.Close()
fso = Nothing
readTextFile = sLine
End Function