错误:文件正由另一个进程使用,即使已关闭并处置

时间:2013-05-23 09:52:17

标签: .net vb.net text-files file-access read-write

我在访问文件时遇到问题。

每1秒(或多或少)我的应用程序调用此过程来下载源代码页并将其保存在文本文件中, 问题是有时当被调用太多时,例如超过50次,我得到错误:

"Can't access file, file it is being used by another process"

我试图关闭它并处理它,但没有。

编辑:导致错误的文件是“OutPutFile”变量,它是%TEMP%目录中的文件。

' Get URL SourceCode
Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing, Optional ByVal delimit As Boolean = False) As String

    Dim SourceCode As String = String.Empty

    If Want_to_cancel_thread Then Return Nothing

    Try
        Dim request As HttpWebRequest = HttpWebRequest.Create(url)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim sr As StreamReader = New StreamReader(response.GetResponseStream())
        SourceCode = sr.ReadToEnd()
        sr.Close() : sr.Dispose()

        If delimit Then SourceCode = Delimit_String(SourceCode, "<div id=""centercol"">", "<!--/centercol -->")

        If OutputFile IsNot Nothing Then

            'File.Open(OutputFile, FileMode.CreateNew, FileAccess.Write, FileShare.Write)
            'Using TextFile As New StreamWriter(OutputFile, False, Encoding.Default)
            '    TextFile.WriteLine(SourceCode)
            'End Using
            File.WriteAllText(OutputFile, SourceCode, Encoding.Default)
        End If

    Catch ex As Exception
        MsgBox("Error: " & ex.Message)
    End Try

    Return SourceCode

End Function

1 个答案:

答案 0 :(得分:1)

尝试使用SyncLock,以便工作线程锁定对象,而其他任何进程都无法访问该文件:

'Global variable lock

Dim objectLock As Object = New Object


Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing, Optional ByVal delimit As Boolean = False) As String

 Dim SourceCode As String = String.Empty

 'Lock object
 SyncLock objectLock 

 If Want_to_cancel_thread Then Return Nothing

    Try
        Dim request As HttpWebRequest = HttpWebRequest.Create(url)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim sr As StreamReader = New StreamReader(response.GetResponseStream())
        SourceCode = sr.ReadToEnd()
        sr.Close() : sr.Dispose()

        If delimit Then SourceCode = Delimit_String(SourceCode, "<div id=""centercol"">", "<!--/centercol -->")

        If OutputFile IsNot Nothing Then

            'File.Open(OutputFile, FileMode.CreateNew, FileAccess.Write, FileShare.Write)
            'Using TextFile As New StreamWriter(OutputFile, False, Encoding.Default)
            '    TextFile.WriteLine(SourceCode)
            'End Using
            File.WriteAllText(OutputFile, SourceCode, Encoding.Default)
        End If

    Catch ex As Exception
        MsgBox("Error: " & ex.Message)
    End Try

    'End lock
    End SyncLock

    Return SourceCode

 End Function