FileInfo 返回错误值?

FileInfo returning wrong value?

好的,所以我在 VB.NET 工作,手动将错误日志写入日志文件(是的,我知道,我没有打电话)。现在,如果文件超过任意大小,当函数开始写出新的错误数据时,它应该使用新文件名启动一个新文件。

函数如下:

        Dim listener As New Logging.FileLogTraceListener
        listener.CustomLocation = System.Configuration.ConfigurationManager.AppSettings("LogDir")
        Dim loc As String = DateTime.UtcNow.Year.ToString + DateTime.UtcNow.Month.ToString + DateTime.UtcNow.Day.ToString + DateTime.UtcNow.Hour.ToString + DateTime.UtcNow.Minute.ToString

        listener.BaseFileName = loc

        Dim logFolder As String
        Dim source As String

        logFolder = ConfigurationManager.AppSettings("LogDir")
        If ex.Data.Item("Source") Is Nothing Then
            source = ex.Source
        Else
            source = ex.Data.Item("Source").ToString
        End If

        Dim errorFileInfo As New FileInfo(listener.FullLogFileName)

        Dim errorLengthInBytes As Long = errorFileInfo.Length


        If (errorLengthInBytes > CType(System.Configuration.ConfigurationManager.AppSettings("maxFileSizeInBytes"), Long)) Then

            listener.BaseFileName = listener.BaseFileName + "1"

        End If


        Dim msg As New System.Text.StringBuilder
        If String.IsNullOrEmpty(logFolder) Then logFolder = ConfigurationManager.AppSettings("LogDir")

        msg.Append(vbCrLf & "Exception" & vbCrLf)
        msg.Append(vbTab & String.Concat("App: AppMonitor | Time: ", Date.Now.ToString) & vbCrLf)
        msg.Append(vbTab & String.Concat("Source: ", source, " | Message: ", ex.Message) & vbCrLf)
        msg.Append(vbTab & "Stack: " & ex.StackTrace & vbCrLf)


        listener.Write(msg.ToString())
        listener.Flush()

        listener.Close()

出于测试目的,我在循环中执行此操作,因此我可以看到当它同时收到(比如说)10000 个错误时会发生什么。同样,我知道有更好的方法来系统地处理这个问题,但这是我被告知要实施的代码。

如何在写入日志文件之前可靠地获取日志文件的大小,就像我在上面尝试做的那样?

好吧,对于很多事情,答案是 "did you read your own code closely" 附带 "eat something, you need to fix your blood sugar."

在审查时,我看到我一直在检查 BaseFileName,如果超过任意限制,则附加一个字符并写入该文件。我没有做的是检查该文件或其他更新的文件是否存在。我已经解决了这个问题,即抓取与 Directory.GetFiles 中的 "BaseFileName*" 参数匹配的所有文件的目录列表,并 selecting 最近访问的文件。这确保记录器将始终 select 要写入的更新文件或 - 如果需要 - 用作另一个附加字符的基本名称。

这是代码:

        Dim directoryFiles() As String = Directory.GetFiles(listener.Location.ToString(), listener.BaseFileName + "*")

        Dim targetFile As String = directoryFiles(0)

        For j As Integer = 1 To directoryFiles.Count - 1 Step 1
            Dim targetFileInfo As New FileInfo(targetFile)
            Dim compareInfo As New FileInfo(directoryFiles(j))

            If (targetFileInfo.LastAccessTimeUtc < compareInfo.LastAccessTimeUtc) Then
                targetFile = directoryFiles(j)
            End If
        Next


        Dim errorFileInfo As New FileInfo(listener.Location.ToString() + targetFile)
        Dim errorLengthInBytes As Long = errorFileInfo.Length