开发者

IO.FileNotFoundException but File should exist

开发者 https://www.devze.com 2023-03-25 00:34 出处:网络
I\'m getting a suprising FileNotFoundException although i\'m sure that the file exists. I simply wanted to add Logfiles(IO.FileInfo) as attachments to an email, therefore i tried to check the length

I'm getting a suprising FileNotFoundException although i'm sure that the file exists.

I simply wanted to add Logfiles(IO.FileInfo) as attachments to an email, therefore i tried to check the length of every file to detect if they must be added/zipped. This works fine if these files already exist. But if i've created them in this run, i get above exception when i try to check the length. It's oddly enough that i can write into these "not existing" files(actually FileInfo.Exists retur开发者_高级运维ns false) without a problem one line before.

Here is some code...

Creating one of the files in the constructor of a class named Log:

Me.LogFile = New IO.FileInfo(infoLogPath)
If Not LogFile.Exists() Then
   'tried to use `Using` on the Stream but that doesn't change anything'
   Using stream = Me.LogFile.Create()
       'close and dispose implicitely
   End Using
End If

I can write into the file without a problem:

Me.Log.WriteInfo("BlahBlahBlah...", False)

One line after i'm getting the exception on LogFile.Length:

If Me.Log.LogFile.Length <> 0 Then
    files.Add(Me.Log.LogFile)
End If

Me.Log is a custom logging-class object named Log that holds the reference to the FileInfo object.

This is WriteInfo in class Log, LogFile is the IO.FileInfo-onject:

Public Sub WriteInfo(ByVal message As String, ByVal finishLog As Boolean)
    Try
        Using w As IO.StreamWriter = Me.LogFile.AppendText
            If Me.WithTimestamp Then
                w.WriteLine(Date.Now.ToString(Globalization.CultureInfo.InvariantCulture) & ": " & message)
            Else
                w.WriteLine(message)
            End If
            If finishLog Then w.WriteLine("__________________________")
            w.Flush()
            w.Close()
        End Using
    Catch writeLogException As Exception
        Try
            WriteError(writeLogException, True)
        Catch innerEx As Exception
            'ignore
        End Try
    End Try
End Sub

Actually @ShellShocks solution with Refresh was simple. Never heard of this function, strange that i get a FileNotFoundException when i don't refresh the file.

Me.Log.LogFile.Refresh()


Try calling FileInfo.Refresh before FileInfo.Exists, or FileInfo.Length--these properties may be cached, so Refresh will get the latest value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号