I have a requirement for a project to take text files from a specific folder and load that data into a sql table then move that file to an archive folder. I do not know what the file name is going to be but I know the data inside will be in the format "Barcode|Carrier". The people delivering this file say they create it and move the file to my specific folder. However, I get an error saying that "The process cannot access the file 'Filename.txt' because it is being used by another process."
So I made some quick modifications to try to handle this but at seemingly random times the files are inserted into the folder and just sit there. Here is my code which has been modified alot in the field. Their files also had some lines (2-4) with no text so I added in that if statement. Also, I want to use the move method, but I was getting errors about the file being open so I write the file to my archive folder and delete the input file.
What can I do to get this to work? Should I just use a timer and poll the folder for new files? Thanks for the help. Also, cmd3 is my stored procedure and works fine.
So I made some quick modifications to try to handle this but at seemingly random times the files are inserted into the folder and just sit there. Here is my code which has been modified alot in the field. Their files also had some lines (2-4) with no text so I added in that if statement. Also, I want to use the move method, but I was getting errors about the file being open so I write the file to my archive folder and delete the input file.
What can I do to get this to work? Should I just use a timer and poll the folder for new files? Thanks for the help. Also, cmd3 is my stored procedure and works fine.
Code:
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created
Dim mypath As String = My.Settings.OrderFilePath
Dim archpath As String = My.Settings.ArchiveFilepath
Dim filename As String = mypath & e.Name
Try
Dim myreader As New System.IO.StreamReader(filename)
Dim location As Integer
Dim barcode, carrier, myinput As String
While myreader.EndOfStream = False
myinput = myreader.ReadLine.ToString
If myinput.Length > 1 Then
System.IO.File.WriteAllText(archpath & e.Name, myinput.ToString)
location = InStr(myinput, "|")
barcode = Mid(myinput, 1, location - 1)
carrier = Mid(myinput, location + 1)
cmd3.Parameters(0).Value = barcode
cmd3.Parameters(1).Value = carrier
cmd3.ExecuteNonQuery()
Else
Exit While
End If
End While
myreader.Close()
System.IO.File.Delete(filename)
'System.IO.File.Move(filename, archpath & e.Name)
Catch ex As Exception
If ex.Message = "The process cannot access the file '" & filename & "' because it is being used by another process." Then
Call FileSystemWatcher1_Changed(sender, e)
End If
'
End Try
End Sub