d0m1n1c d0m1n1c - 4 years ago 196
Vb.net Question

Why is it that the LastWriteTime of a file and the stored Date&Time of that same file don't equal, even if are the same?

I'm trying to notify users there has been a change to a file, by making a picturebox turn lime when the date in the application's settings is not equal to the LastWriteTime of a file. However, when i run the program and the two are equal (to my knowledge) it still says they are not equal. I've added a textbox in order to visualize it, but I don't know what I'm doing wrong...

My code:

fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
If Not My.Settings.fsw_wevelSTX_lastwrite = fsw_wervelSTX_file.LastWriteTime Then
PictureBox_wervelSTX.BackColor = Color.Lime
MsgBox("Time in My.Settings: " & My.Settings.fsw_wevelSTX_lastwrite & " LastWriteTime: " & fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
PictureBox_wervelSTX.BackColor = Color.Maroon
MsgBox("It is the same", MsgBoxStyle.Information)
End If

There's a screenshot of the MsgBox in the link:

The LastWriteTime is stored to My.Settings when the user clicks the button to open the specified file:


Private Sub Button11_Click(sender As System.Object, e As System.EventArgs) Handles Button11.Click
PictureBox_wervelSTX.BackColor = Color.Maroon
fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
MsgBox(fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
My.Settings.fsw_wevelSTX_lastwrite = fsw_wervelSTX_file.LastWriteTime
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub

Thanks in advance.

Answer Source

Going from the code you posted I guess it's a serialization thing. The datetime is probably stored in your settings as something like 2016-01-06 12:08:11 (aside the actual date formatting) whereas the actual datetime probably has more/better 'resolution' and contains something like 2016-01-06 12:08:11.123. I'd suggest one of:

  • Storing it in a specific (specified) format and make sure you compare no more than the actual stored 'resolution'
  • Storing the value as ticks or some other specific long/integer value (e.g. UNIX timestamp for example)
  • Allow for some 'margin' when comparing

Which is best is up to you and the requirements / usecases.

There's all sorts of weird things with file datetimes like Why does the timestamp of a file increase by up to 2 seconds when I copy it to a USB thumb drive? but my best guess currently is that you're just comparing two slightly different values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download