Read a text file which contains SQL code to create tables in a database - vb.net

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

Related

File can't be accessed because it's already in use

I have a Sub that reads a file that was created in another Sub. I'm getting an error
Can't access file in use in other process
From what I've read on the net I need to close the StreamReader. I've tried to use .close() on different variables, but nothing seems to work.
Below is the code that writes the file the other Sub then accesses.
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
strGraphicFile = MoveLocation & "\ICN-LIST.txt"
Dim ICNFiles = Directory.EnumerateFiles(MovePath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
output.Add(match.Groups(1).Value)
End If
Next
File.WriteAllLines(strGraphicFile, output)
locationGraphicsLog = strGraphicFile
End Sub
The other Sub that reads the file created
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sGraphicFilesToFind As String
Dim graphicLocation As String
'MoveWithPath As String
Dim graphicFile As String
graphicLocation = txtSearchICN.Text
MoveLocation = MovePath
graphicLogFile = MoveLocation & "\Reports\1-OrphanedFilesItems.txt"
Dim FILE_NAME As String
FILE_NAME = MoveLocation & "\ICN-LIST.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sGraphicFile As String
Do While objReader.Peek() <> -1
graphicFile = objReader.ReadLine()
sGraphicFilesToFind = graphicLocation & "\" & graphicFile & "*.*"
sGraphicFile = graphicFile
Dim createGraphicReportFldr As String
Dim paths() As String = IO.Directory.GetFiles(graphicLocation, sGraphicFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
'Debug.Print(graphicFile)
If System.IO.File.Exists(graphicLogFile) = True Then
Dim objWriter As New System.IO.StreamWriter(graphicLogFile, IO.FileMode.Append)
objWriter.WriteLine(graphicFile)
objWriter.Close()
Else
'MsgBox("Creating Orphaned graphicFile Now. ")
createGraphicReportFldr = MoveLocation & "\Reports"
If Not IO.Directory.Exists(createGraphicReportFldr) Then
IO.Directory.CreateDirectory(createGraphicReportFldr)
'MsgBox("folder created" & createGraphicReportFldr)
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(graphicLogFile)
writeFile.Write(graphicFile & vbCrLf)
writeFile.Close()
Else
'MsgBox("Folder already exist")
End If
End If
Else
For Each pathAndFileName As String In paths
Dim createGraphicsFolder As String
'Dim moveFileToNewFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toGraphiicFileLocation As String
'MsgBox("sRegLast " & sRegLast)
fileGraphicLoc = MoveLocation & sRegLast
createGraphicsFolder = MoveLocation & "\Figures"
moveGraphicFileToNewFolder = MoveLocation & "\Figures\" & sRegLast
toGraphiicFileLocation = createGraphicsFolder & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
If Not IO.Directory.Exists(createGraphicsFolder) Then
IO.Directory.CreateDirectory(createGraphicsFolder)
' MsgBox("folder created" & createGraphicsFolder)
End If
If System.IO.File.Exists(fileGraphicLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveGraphicFileToNewFolder)
Debug.Write("Graphics moved to : " & moveGraphicFileToNewFolder & vbCrLf)
End If
End If
Next
End If
Loop
'MsgBox("graphicFiles have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
In the "other Sub", change
Dim objReader As New System.IO.StreamReader(FILE_NAME)
to
Using objReader = New System.IO.StreamReader(FILE_NAME)
and add End Using where you are done with it. Probably right after Loop. This will ensure that the disposable stream is always disposed.
See Using Statement (Visual Basic). You almost always want to wrap an IDisposable object in a Using block if you are able to restrict its scope to a single method.

How can creating dbf file, and define encoding in Notepad, or VBA

what is DBF4 (dBase IV)(*.dbf) file fundamental format? And how can create these file in a same word editor as Notepad with typing?(Update:, or excel VBA?)
What is that's format specifications as:
Delimiter (Same as: , or tab or etc)
Separator (may Same as above!) (If these two are not synonymy)
Row End character: (Same as vbCrLf)
Defining headers of columns(fields).
Code-Page of encoding: (same as: Unicode - 1256 or etc)
and others...
Please present an algorithm for creating this DB file format that made us able to create a same file easily by a VBA method which creates a text file.
(Update Or using built-in VBA or its references methods.)
I using below for creating text file.
Sub CsvExportRange(rngRange As Object, strFileName As String, strCharset, strSeparator As String, strRowEnd As String, NVC As Boolean) 'NVC: _
Null Value Control (If cell contain Null value, suppose reached end of range), d: delimiter
Dim rngRow As Range
Dim objStream As Object
Dim i, lngFR, lngLR As Long 'lngFR: First Row, lngLR: Last Row
lngFR = rngRange.SpecialCells(xlCellTypeVisible).Rows(1).row - rngRange.Rows(1).row + 1
lngLR = rngRange.End(xlDown).row - rngRange.Rows(1).row + 1
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Charset = strCharset
objStream.Open
For i = lngFR To lngLR
If Not (rngRange.Rows(i).EntireRow.Hidden) Then
If IIf(NVC, (Cells(i + rngRange.Rows(1).row - 1, _
rngRange.SpecialCells(xlCellTypeVisible).Columns(1).column).Value = vbNullString), False) Then Exit For
objStream.WriteText CsvFormatRow(rngRange.Rows(i), strSeparator, strRowEnd)
End If
Next i
objStream.SaveToFile strFileName, 2
objStream.Close
End Sub
Function CsvFormatRow(rngRow As Variant, strSeparator As String, strRowEnd As String) As String
Dim arrCsvRow() As String
ReDim arrCsvRow(rngRow.SpecialCells(xlCellTypeVisible).Cells.Count - 1)
Dim rngCell As Range
Dim lngIndex As Long
lngIndex = 0
For Each rngCell In rngRow.SpecialCells(xlCellTypeVisible).Cells
arrCsvRow(lngIndex) = CsvFormatString(rngCell.Value, strSeparator)
lngIndex = lngIndex + 1
Next rngCell
CsvFormatRow = Join(arrCsvRow, strSeparator) & strRowEnd
End Function
Function CsvFormatString(strRaw, strSeparator As String) As String
Dim boolNeedsDelimiting As Boolean
Dim strDelimiter, strDelimiterEscaped As String
strDelimiter = """"
strDelimiterEscaped = strDelimiter & strDelimiter
boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _
Or InStr(1, strRaw, chr(10)) > 0 _
Or InStr(1, strRaw, strSeparator) > 0
CsvFormatString = strRaw
If boolNeedsDelimiting Then
CsvFormatString = strDelimiter & _
Replace(strRaw, strDelimiter, strDelimiterEscaped) & _
strDelimiter
End If
End Function
(Forgotten source)
Because I reached this: I should create a dbf file from my Excel Range by hand! After searching founded web sources.
Updated:
How can declare encoding of DBF?
About encoding that needed, considerable ones is Commonplace in this issue is Iran System encoding.
How can I store data with suitable encoding as Iran System in DB table records?
we have joy .... lol
this test code creates a dbf file from data in excel worksheet
creates a table and inserts one record
Sub dbfTest()
' NOTE: put this test data at top of worksheet (A1:F2)
' Name Date Code Date2 Description Amount
' frank 11/12/2017 234.00 11/20/2018 paint $1.34
' ref: microsoft activex data objects
Dim path As String
Dim fileName As String
filePath = "C:\database\"
fileName = "test"
Dim dc As Range
Dim typ As String
Dim fieldName As String
Dim createSql As String
createSql = "create table " + fileName + " (" ' the create table query produces the file in directory
Dim a As Variant
For Each dc In Range("a1:e1")
fieldName = dc.Value
a = dc.offset(1).Value
Select Case VarType(a)
Case vbString: typ = "varchar(100)"
Case vbBoolean: typ = "varchar(10)"
Case vbInteger: typ = "int"
Case vbLong: typ = "Double"
Case vbDate: typ = "TimeStamp"
Case Else: typ = "varchar(5)" ' default for undefined types
End Select
createSql = createSql + " [" + fieldName + "]" + " " + typ + ","
Next dc
createSql = Left(createSql, Len(createSql) - 1) + ")"
Debug.Print createSql
Dim conn As ADODB.connection
Set conn = CreateObject("ADODB.Connection")
conn.Open "DRIVER={Microsoft dBase Driver (*.dbf)};" & "DBQ=" & filePath ' both work
' conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=dBASE IV"
Dim cmd As ADODB.Command
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = createSql
cmd.Execute
Dim insertSql As String
insertSql = "insert into " + fileName + " values("
For Each dc In Range("a2:e2")
insertSql = insertSql + "'" + CStr(dc.Value) + "',"
Next dc
insertSql = Left(insertSql, Len(insertSql) - 1) + ")"
Debug.Print insertSql
cmd.CommandText = insertSql
cmd.Execute
conn.Close
Set conn = Nothing
End Sub
my research has concluded. the Iran System encoding is actually ascii, it is not unicode. it uses ascii values to represent some of the Persian alphabet.
the problem with converting from unicode to Iran System encoding is that any letter is written completely differently depending where in the word it is positioned. you have "isolated", "initial", "medial" and "final" forms of most of the letters.
it is like upper and lower case on steroids ... lol
ref: https://www.math.nmsu.edu/~mleisher/Software/csets/IRANSYSTEM.TXT
so additional process would be needed to convert unicode text in excel into an equivalent Iran System encoding string before storing in database.
the code creates a table with one text field and stores 3 records
Sub dbfTestWork()
' ref: microsoft activex data objects
Dim filePath As String
Dim fileName As String
filePath = "C:\database\"
fileName = "test"
Dim conn As ADODB.Connection
Set conn = CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft dBase Driver (*.dbf)};Dbq=" + filePath + ";"
'conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=dBASE IV;"
Dim fil As String
fil = filePath & fileName & ".dbf"
If Not Dir(fil, vbDirectory) = vbNullString Then Kill fil ' delete file if it exists
Dim cmd As ADODB.Command
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = "create table test ([testTextData] char(20))"
cmd.Execute
Dim nFileNum As Integer
nFileNum = FreeFile ' Get an available file number from the system
Open filePath & fileName & ".dbf" For Binary Lock Read Write As #nFileNum ' Open the file in binary mode. Locks are optional
Put #nFileNum, 30, CByte(1) ' set language driver id (LDID) 0x01 = ascii encoding
Close #nFileNum
' Debug.Print Range("e2").Value
Dim aaa As String
aaa = StrConv(Range("e2").Value, vbUnicode)
' Debug.Print aaa
Dim cmdStr As String
cmdStr = "insert into test values ('"
Dim ccc As Variant
For Each ccc In Array("ac", "92", "9e", "20", "93", "a1", "fe", "a4") ' one of these two should store
cmdStr = cmdStr & Chr(CDec("&h" & ccc)) ' "good morning" in persian
Next ccc
cmdStr = cmdStr & "');"
cmd.CommandText = cmdStr
cmd.Execute
cmdStr = "insert into test values ('"
For Each ccc In Array("a4", "fe", "a1", "93", "20", "9e", "92", "ac")
cmdStr = cmdStr & Chr(CDec("&h" & ccc))
Next ccc
cmdStr = cmdStr & "');"
cmd.CommandText = cmdStr
cmd.Execute
cmd.CommandText = "insert into test values ('abc123');"
cmd.Execute
conn.Close
Set conn = Nothing
End Sub
'

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...

Update software function doesn't work if software is already open

I've a function that check update for my application. I've two mode for execute this function, in the first time that the application's start and in the tooltip menu. If I execute the software for the first time all working good, the update is found , but if I press on my button in the tooltip menu the same function (the exact function) not working. In particular the update is found but the software for download it (infinity blue) doesn't start.
This is the function:
Dim MyAppName As String = "Sund.exe"
Dim url As String = "www.site.com/update/" & "FileUpdates371.php"
Dim pageRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim pageResponse As WebResponse = pageRequest.GetResponse()
Dim filelist As String : Dim Mainlist As String
Using r As New StreamReader(pageResponse.GetResponseStream())
filelist = r.ReadToEnd
If Not IO.File.Exists(Application.StartupPath & "\" & "Updates") Then
IO.File.WriteAllText(Application.StartupPath & "\" & "Updates", filelist)
End If
Dim sr As New StreamReader(Application.StartupPath & "\" & "Updates")
Mainlist = sr.ReadToEnd
Dim FileLines() As String = filelist.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim MainLines() As String = Mainlist.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
If Not Mainlist = filelist And Not FileLines.Length < MainLines.Length Then
Dim answer As DialogResult
answer = MessageBox.Show("Update available", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If answer = vbYes Then
Dim App As New Process
App.StartInfo.FileName = Application.StartupPath & "\" & "InfinityBlue.exe"
App.StartInfo.Arguments = "Update|" & MyAppName & "|" & url
App.Start()
Me.Close()
End If
End If
End Using
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\" & "InfinityBlueUpdate.exe") Then
My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\" & "InfinityBlue.exe", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
My.Computer.FileSystem.RenameFile(Application.StartupPath & "\" & "InfinityBlueUpdate.exe", "InfinityBlue.exe")
End If
I've also tried to catch the exception and there isn't exception. Why happean this?

How to Request a File from FTP Using Today's Date as part of Filename?

We have a service that provides several files per day for pickup. Each file is appended with today's date and the hours, minutes, seconds and milliseconds stamp of the time the file was created.
Our goal is to download all files for a given day regardless of the time stamp. I've set the following variable:
Dim remoteFile As String = "/datafeed/sdlookup-total-" & DateTime.Today.Year.ToString
& "-" & DateTime.Today.Month.ToString("0#") & "-" & DateTime.Today.Day.ToString("0#") &
".csv.zip"
When I run the console application, I receive a HTTP 550 file not found because the files on the FTP all have the timestamp after the day e.g.
sdlookup-total-2013-07-27_02_15_00_272.csv.zip
The Module is as follows:
Imports System.IO
Imports System.IO.Compression
Imports System.Net
Imports System.Net.WebClient
' This module when run will download the file specified and save it to the local path as defined.
Module Module1
Dim Today As Date = Now()
' Change the value of localFile to the desired local path and filename
Dim localFile As String = "C:\ForeclosureFile\sdlookoup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
' Change the value of remoteFile to the desired filename
Dim remoteFile As String = "/datafeed/sdlookup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Const host As String = "ftp://Datafeed.foreclosure.com"
Const username As String = "sdlookup"
Const pw As String = "ourpass"
Dim strDownLoadTemplate = "sdlookup-total-" & Today.Year.ToString & "-" & Today.Month.ToString
("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Dim strCleanFileForDTS As String
Dim strLocalZipFile = "C:\ForeclosureFile\ForeclosureFull.zip"
Dim strLocalCSVFile = "C:\ForeclosureFile\Foreclosurefull.csv"
Sub Main()
Dim URI As String = host + remoteFile
Dim req As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
req.Credentials = New NetworkCredential(username, pw)
req.KeepAlive = False
req.UseBinary = True
req.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(req.GetResponse,
System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
Dim zipPath As String = "C:\ForeclosureFile\"
Dim extractPath As String = "C:\ForeclousreFile"
ZipFile.ExtractToDirectory(zipPath, extractPath)
End Sub
Sub ProcessFile()
'Downloaded file
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim strLocalCSVFile As String = "C:\ForeclosureFile\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim strCleanFileForDTS As String = "C:\ForeclosureFile\ForDTS\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim LineIn As String
'Dim Fields() As String
'New File
Dim oNewFile As System.IO.File
Dim oWrite As System.IO.StreamWriter
oWrite = File.CreateText(localFile & strCleanFileForDTS)
oRead = File.OpenText(localFile & strLocalCSVFile)
' strLocalCSVFile()
While oRead.Peek <> -1
'While oRead.
LineIn = oRead.ReadLine()
'Fixes file problem
oWrite.WriteLine(Replace(LineIn, """", "", 1))
End While
oRead.Close()
oWrite.Close()
End Sub
Sub FTPFileDownload(strtFetchFile As String, PathToSave As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter
Dim strFullPathandFile As String
strFullPathandFile = PathToSave & strtFetchFile
myFtpWebRequest = WebRequest.Create("ftp://Datafeed.foreclosure.com/datafeed/" &
strtFetchFile)
myFtpWebRequest.Credentials = New NetworkCredential("sdlookup", "ohpaiH1b")
myFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile
myFtpWebRequest.UseBinary = True
myFtpWebRequest.UsePassive = True
myFtpWebResponse = myFtpWebRequest.GetResponse()
PathToSave = "D:\test.zip"
myStreamWriter = New StreamWriter(PathToSave)
myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)
myStreamWriter.Close()
' litResponse.Text = myFtpWebResponse.StatusDescription
myFtpWebResponse.Close()
End Sub
Public Sub DownloadFiles(ByVal Wildcard As String)
Wildcard = "sdlookup-total-*.csv.zip"
Dim Files As String() = GetFiles(Wildcard)
For Each file As String In Files
DownloadFile(file)
Next
End Sub
End Module
How should I modify the above module so that all files containing sdlookup-total-"Today'sDate".csv.zip regardless of timestamp are downloaded each time the module is executed?