0

我注意到我的雾虫报告中有很多“无法访问文件,因为它正被另一个进程使用”错误。我猜这可能与文件打开后未关闭有关。或者保存后不被关闭。任何人都可以验证这是否是我的问题并建议我更好的解决方法。

在表单加载时打开此文件,并在关闭时保存文件。

表单加载

   If IO.File.Exists(myCoolFile) Then '// check if file exists.
            Dim myCoolFileLines() As String = IO.File.ReadAllLines(myCoolFile) '// load your file as a string array.
            For Each line As String In myCoolFileLines '// loop thru array list.
                Dim lineArray() As String = line.Split("#") '// separate by "#" character.
                'Dim newItem As New ListViewItem(lineArray(0)) '// add text Item.
                ' ListView1.Items.Add(newItem) '// add Item to ListView.
                ListView1.Items.Add(lineArray(0)).Tag = (lineArray(1))
            Next

        Else
            If Not File.Exists(myCoolFile) Then
                File.Create(myCoolFile)
                End If

表格关闭

     Dim myWriter As New IO.StreamWriter(myCoolFile)
        For Each myItem As ListViewItem In ListView1.Items
            myWriter.WriteLine(myItem.Text & "#" & myItem.Tag) '// write Item and SubItem.
        Next
        myWriter.Close()
4

1 回答 1

0

A better solution would be to use a database.

Here is code to check if the files is open by another process (you could perhaps wait a small amount of time and retry saving again once or twice):

Private Sub IsFileOpen(ByVal file As FileInfo)
    Dim stream As FileStream = Nothing
    Try
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
    Catch ex As Exception

        If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
            ' do something here, either close the file if you have a handle or as a last resort terminate the process - which could cause corruption and lose data
        End If
    End Try
End Sub

Private Shared Function IsFileLocked(exception As Exception) As Boolean
    Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
    Return errorCode = 32 OrElse errorCode = 33
End Function
于 2012-11-27T05:48:56.113 回答