释放文件锁

Releasing File Locks

我有一个后台工作程序 运行 程序的一部分,它循环遍历在 运行 时间整理的文件数组,根据文件类型等执行各种 SQL 任务。

一个接一个,随着文件的处理,我想把它们移到另一个文件夹,以免不小心被重新处理。

进程的某些部分正在锁定文件,因为循环末尾的移动命令因锁定而失败。释放锁(如果有的话)然后移动文件的最佳方法是什么?我考虑过复制然后删除,但我怀疑删除源文件也会有同样的问题。

子文件计数 (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

后台工作者代码。

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

DO STUFF HERE 做以下两件事之一 - 将 .csv 文件读入 DataTable(数据使用 FileIO.TextFieldParser 写入)或使用 System.IO.MemoryStream.

将图像转换为字节码

在这两种情况下,数据都被写入 SQLite table。

正如 Chris Dunaway 所暗示的,答案是在尝试移动文件之前 close() 相应图像的 TextFieldParser 和 Dispose