关闭表单时卸载CSV文件

yjghlzjz  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(71)

在我的应用程序中,我有一个从csv文件导入到mysql的表单。但是当我关闭它时,csv文件仍然在我的应用程序中使用。
这里是CSV导入的代码:

Private Sub Btn_brow_Click(sender As Object, e As EventArgs) Handles Btn_brow.Click
        Dim ofd As New OpenFileDialog
        Dim dt As New DataTable

        Try
            With ofd
                .Filter = "CSV files(*.csv)|*.csv"
                .FilterIndex = 1
                .Title = "Import data from CSV File"
            End With
            If ofd.ShowDialog() = DialogResult.OK Then
                txtLocation.Text = ofd.FileName

                Dim sr As New IO.StreamReader(ofd.FileName)

                Dim newline() As String = sr.ReadLine.Split(";"c)
                dt.Columns.AddRange({New DataColumn(newline(0)), New DataColumn(newline(1)), New DataColumn(newline(2)), New DataColumn(newline(3))})
                While (Not sr.EndOfStream)
                    newline = sr.ReadLine.Split(";"c)
                    Dim newrow As DataRow = dt.NewRow
                    newrow.ItemArray = {newline(0), newline(1), newline(2), newline(3)}
                    dt.Rows.Add(newrow)
                End While
                Dgv_Import.DataSource = dt

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
carvr3hs

carvr3hs1#

Dim sr As New IO.StreamReader(ofd.FileName)行替换为Using sr As IO.StreamReader = New IO.StreamReader(ofd.FileName)行如何?然后在End While后添加End Using
这将在处理完StreamReader对象后自动释放它。

相关问题