简体   繁体   中英

Accessing same file from multiple instances of application

I have noticed alot of "Cannot access file because it is being used by another process" errors in my fogbugz reports. I am geussing this might have to do with the file not being closed after it has been opened. Or not being closed after a save. Can anyone verify if this is my issue and advise me a better way to go about it.

On form load this file is opened, and on close the file is saved.

Form Load

   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

Form Close

     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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM