-
Nov 27th, 2014, 04:31 AM
#1
Thread Starter
Junior Member
How to insert a blank file check ?
Hi Guys,
I have this code which updates SQL database using the files in a folder and delete them after update but its giving me an exception whenever the blank file is found in the folder. It gives error " The object reference not set to Instance of an object" . What i really want to do is before processing each file i need to check each file if its blank then delete it otherwise process it. this is the code :
Any help will be much appreciated.
Code:
Dim dirinfo5 As DirectoryInfo
Dim allFiles5() As FileInfo
dirinfo5 = New DirectoryInfo("E:\UPDATE\")
allFiles5 = dirinfo5.GetFiles("*.csv")
Thread.Sleep(1000)
If allFiles5.Length <> 0 Then
Try
For Each fl5 As FileInfo In allFiles5
'MsgBox(fl.FullName.ToString())
Dim con As SqlConnection = New SqlConnection(SQL_con2)
Dim sr As StreamReader = New StreamReader(fl5.FullName)
Dim line As String = sr.ReadLine
Dim value() As String = line.Split(Microsoft.VisualBasic.ChrW(44))
Dim dt As DataTable = New DataTable
Dim row As DataRow
For Each dc As String In value
dt.Columns.Add(New DataColumn(dc))
Next
While Not sr.EndOfStream
value = sr.ReadLine.Split(Microsoft.VisualBasic.ChrW(44))
If (value.Length = dt.Columns.Count) Then
row = dt.NewRow
row.ItemArray = value
dt.Rows.Add(row)
End If
End While
Dim bc As SqlBulkCopy = New SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock)
bc.DestinationTableName = "[DB].[dbo].[LData]"
bc.BatchSize = dt.Rows.Count
con.Open()
bc.WriteToServer(dt)
bc.Close()
con.Close()
sr.Close()
System.IO.File.Delete(fl5.FullName)
sr.Dispose()
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
-
Nov 27th, 2014, 04:52 AM
#2
Re: How to insert a blank file check ?
Hi,
You do not need to write an “Empty File Checker”, you just need to write your routine correctly. The reason why you are getting this error is because you call the ReadLine and Split methods on the Streamreader before you actually check if the Streamreader is at the EndOfStream.
Your code should really look something like:-
vb.net Code:
For Each currentFile As String In Directory.GetFiles("SomePath") Using myReader As New StreamReader(currentFile) While Not myReader.EndOfStream Dim someText As String = myReader.ReadLine 'Do some work with each of the lines read from the file End While End Using Next
As you can see, we get some files from a Directory, open the file, check for EndOfStream first and then do some work with the file if necessary.
Hope that helps.
Cheers,
Ian
-
Nov 27th, 2014, 09:23 AM
#3
Thread Starter
Junior Member
Re: How to insert a blank file check ?
Hi Ian,
Thanks for your reply. I will give it a go
Cheers
Bilal
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|