从多个应用程序实例访问相同的文件

时间:2012-11-27 04:41:36

标签: .net vb.net visual-studio-2010 file-io

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

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

表单加载

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

1 个答案:

答案 0 :(得分:0)

更好的解决方案是使用数据库。

以下是检查文件是否被其他进程打开的代码(您可能需要等待一小段时间再重试一次或两次):

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