title: The process cannot access the file 'file.csv' because it is being used by another process
body: <p>I have a code which process each file in a folder and send the data in the file to SQL Database and then deletes the file. But often i get this Exception "The process cannot access the file 'file.csv' because it is being used by another process." Please can anyone point me out in the right direction, will really appreciate that.</p>
  
  <p>The code is shown below :</p>
  
  <pre><code>    Dim dirinfo As DirectoryInfo
      Dim allFiles() As FileInfo
  
      dirinfo = New DirectoryInfo("E:\SQLUPDATE\CAC")
      allFiles = dirinfo.GetFiles("*.csv")
      If allFiles.Length &lt;&gt; 0 Then
          Try
              For Each fl As FileInfo In allFiles
                  'MsgBox(fl.FullName.ToString())
                  Dim con As SqlConnection = New SqlConnection(SQL_con2)
                  Dim sr As StreamReader = New StreamReader(fl.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].[CAC_LData]"
                  bc.BatchSize = dt.Rows.Count
                  con.Open()
                  bc.WriteToServer(dt)
                  bc.Close()
                  con.Close()
                  sr.Close()
                  System.IO.File.Delete(fl.FullName)
                  sr.Dispose()
              Next
          Catch ex As Exception
              MsgBox(ex.Message)
          End Try
      End If
  </code></pre>