0
votes

when I write to my log file I sometimes get access to log path is denied C:/app/log.log

Here is my code:

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

Is there anyway to make this use admin permissions or fix this issue? It only happens sometimes, and I'm not sure why it happens, but if I delete the log.log file the application can write to log again. Very weird.

1
If it works sometimes, it is probably not a permissions issue, but rather an "in use" issue. I'm surprised you're not having permissions issues. Applications should not be able to write to a root directory of the C:\ drive. Write log files into AppData instead.Cody Gray♦
Since you create a new filestream everytime you write to it, why do you also have it as a public variable that is never disposed?Ňɏssa Pøngjǣrdenlarp

1 Answers

0
votes

You are calling your function WriteLog from multiple threads asynchronously, you should protect this function for example with a mutex.