【问题标题】:Accessing same file from multiple instances of application从多个应用程序实例访问同一个文件
【发布时间】:2012-11-27 04:41:36
【问题描述】:

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

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

表单加载

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

【问题讨论】:

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


    【解决方案1】:

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

    这里是检查文件是否被另一个进程打开的代码(你可能会等待一小段时间,然后重试保存一次或两次):

    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
    

    【讨论】:

    • 在这种情况下,我绝对可以使用数据库。感谢该代码,尽管它可以帮助我处理问题。
    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多