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
returns 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()
What Causes FileNotFoundException. There are two main scenarios when the FileNotFoundException occurs: If a file with the specified pathname does not exist. If a file with the specified pathname is inaccessible, for example, if the file is read-only and is attempted to be opened for writing.
FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn't occur.
IOException is the base class of a lot of checked exceptions which are thrown while reading files, directories, and streams. The try and catch block is used to avoid IOException. FileNotFoundException, UnsupportedEncodingException, DirectoryNotFoundException are some of the subclasses of IOException class.
Try calling FileInfo.Refresh before FileInfo.Exists, or FileInfo.Length--these properties may be cached, so Refresh will get the latest value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With