Vba – writing file in %TEMP% fails silently

vb6vbawindows-server-2008

I have this function which writes to my log file. It is failing silently. In that there are no errors raised in this function, it just fails to create or write to the file. I'm trying to write to %TEMP%\myappname.log. It also fails in %USERPROFILE%\Desktop\myappname.log. Server is Windows Server 2008 R2 Standard.
I've encountered this with writing to the application folder with other programs so moved to writing to the %TEMP% directory and this solved it. But this system won't even let me write to the %TEMP% directory.
Yes I tried running as administrator too and it didn't help.
%TEMP% in this case resolves through ExpandEnvironmentStrings to C:\Users\sa\AppData\Local\Temp\2
So g_strLogPath is C:\Users\sa\AppData\Local\Temp\2\myappname.log.

Public Function LogMessage(ByVal strInput As String, Optional ByVal blnDate As Boolean = False) As Boolean

   Dim intFileNumber As Integer

   On Error GoTo ErrorHandler

   If g_lngLogLevel <> 1 Then
      Exit Function
   End If

   If Len(g_strLogPath) = 0 Then
      SetLogPath
   End If

   If blnDate Then
      strInput = Format(Now, cstrLogDateFormat) & " : " & strInput
   End If

   intFileNumber = FreeFile
   Open g_strLogPath For Append As #intFileNumber
   Print #intFileNumber, strInput
   Close #intFileNumber

   LogMessage = True

   Exit Function

ErrorHandler:

   MsgBox _
      "Error: " & Err.Number & vbCrLf & _
      "Location: Module1.LogMessage" & vbCrLf & _
      "Line: " & Erl & vbCrLf & _
      Err.Description, vbExclamation + vbOKOnly

End Function

Best Solution

Try this

Sub GetTmpPath()
    'This will give the Temp Path
    MsgBox IIf(Environ$("tmp") <> "", Environ$("tmp"), Environ$("temp"))
End Sub

So you can try using it as

    Ret = IIf(Environ$("tmp") <> "", Environ$("tmp"), Environ$("temp"))

    g_strLogPath = Ret & "\Sample.Log"

    Open g_strLogPath For Append As #intFileNumber
Related Question