访问路径日志被随机拒绝

时间:2016-03-11 15:56:44

标签: vb.net

当我写入我的日志文件时,我有时会访问日志路径被拒绝C:/app/log.log

这是我的代码:

Private filePath As String
Private fileStream As FileStream
Private streamWriter As StreamWriter

Public Sub OpenFile()
    Dim strPath As String
    strPath = My.Application.Info.DirectoryPath + "\log.log"
    If System.IO.File.Exists(strPath) Then
        fileStream = New FileStream(strPath, FileMode.Append, FileAccess.Write)
    Else
        fileStream = New FileStream(strPath, FileMode.Create, FileAccess.Write)
    End If
    streamWriter = New StreamWriter(fileStream)
End Sub

Public Sub WriteLog(ByVal strComments As String)
    OpenFile()
    streamWriter.WriteLine(Date.Now.ToString & " " & strComments)
    CloseFile()
End Sub

Public Sub CloseFile()
    streamWriter.Close()
    fileStream.Close()
End Sub

是否有使用此管理员权限或修复此问题?它有时只会发生,我不确定它为什么会发生,但如果删除log.log文件,应用程序可以再次写入日志。非常奇怪。

1 个答案:

答案 0 :(得分:0)

您正在异步地从多个线程调用函数WriteLog,您应该使用互斥锁来保护此函数。