vb.netbackgroundworkermovefile

Releasing File Locks


I have a Background Worker run part of a program that loops through an array of files collated at runtime, doing various SQL tasks based on the file type etc.

One by one, as the files are dealt with, I want to move them to another folder so they are not accidentally reprocessed.

Some part of the process is locking the file(s) as the move command at the end of the loop is failing with a lock. What is the best way of releasing the lock (if there is one) and then moving the file? I considered copy then delete, but I suspect it will have the same issue with deleting the source file.

Count Files Sub (source)

Public Function count_files(ByVal location As String, ByVal Filter As String, ByVal searchOption As System.IO.SearchOption) As String()
        ' ArrayList will hold all file names
        Dim alFiles As ArrayList = New ArrayList()

    ' Create an array of filter string
    Dim MultipleFilters() As String = Filter.Split("|")

    ' for each filter find mathing file names
    For Each FileFilter As String In MultipleFilters
        ' add found file names to array list
        alFiles.AddRange(Directory.GetFiles(location, FileFilter, searchOption))
    Next

    ' returns string array of relevant file names
    Return alFiles.ToArray(Type.GetType("System.String"))
End Function

Background Worker code.

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

'Count File Types, work out total & assign to progress bar length.
progress_total = sFiles.Count
current_count = 0

For Each FileName As String In sFiles
        current_count += 1
        currentfile = FileName
        filenamenoext = Path.GetFileNameWithoutExtension(FileName)
        extension = GetExtension(FileName)
        **DO STUFF HERE**

        'Report Progress

        BackgroundWorker1.ReportProgress(Convert.ToInt32((current_count / progress_total) * 100))

        'If we've reached here, we've done something with the file. Move it so it cannot be reprocessed without manually moving the file.
        Try
        My.Computer.FileSystem.MoveFile(currentfile, Import_Path & "processed\" & filenamenoext & extension, True)

        Catch ex As Exception
        MessageBox.Show(ex.Message, "Error Moving File", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

        System.Threading.Thread.Sleep(100)

Next

End Sub

The DO STUFF HERE does one of two things - read a .csv file into a DataTable (Data is written in using FileIO.TextFieldParser) or convert an image into byte code using System.IO.MemoryStream.

In both cases, the data is written into a SQLite table.


Solution

  • As hinted by Chris Dunaway, the answer was to close() the TextFieldParser and Dispose of the respective Image before trying to move the file.