vbnet
  1. vbnet-date-time

File Handling in VB.NET Date & Time

In VB.NET, you can use file handling to work with files and directories. This includes reading and writing to files, creating, copying, and deleting files and directories. In this page, we will focus on how to work with date and time when using file handling in VB.NET.

Syntax

To work with date and time in file handling, you can use the File.GetCreationTime and File.GetLastWriteTime methods. These methods return the creation and last write time of a file, respectively. Here is the syntax for using these methods:

Dim creationTime As DateTime = File.GetCreationTime("path/to/file")
Dim lastWriteTime As DateTime = File.GetLastWriteTime("path/to/file")

Example

Here's an example of how to use the File.GetCreationTime and File.GetLastWriteTime methods to get the creation and last write time of a file:

Imports System.IO

Module FileDateAndTimeDemo

    Sub Main()

        Dim file As String = "C:\test.txt"

        If File.Exists(file) Then
            Dim creationTime As DateTime = File.GetCreationTime(file)
            Console.WriteLine("File created at: " & creationTime)

            Dim lastWriteTime As DateTime = File.GetLastWriteTime(file)
            Console.WriteLine("Last write time: " & lastWriteTime)

        Else
            Console.WriteLine("File does not exist.")
        End If

    End Sub

End Module

Output

When you run the above code, it will output the creation time and last write time of the specified file.

File created at: 4/19/2021 2:31:37 PM
Last write time: 4/20/2021 10:02:57 AM

Explanation

The File.GetCreationTime and File.GetLastWriteTime methods return the creation and last write time of a file, respectively. In the example code above, we first check if the file exists using the File.Exists method. If the file exists, we retrieve the creation and last write time of the file using the File.GetCreationTime and File.GetLastWriteTime methods, respectively. Finally, we output the retrieved date and time values to the console.

Use

Working with date and time in file handling can be useful when you need to keep track of when a file was created or modified. This information can be used for various purposes, such as logging, version control, and auditing.

Important Points

  • VB.NET provides the File.GetCreationTime and File.GetLastWriteTime methods to work with file date and time.
  • The returned date and time values are of the DateTime data type.

Summary

In this page, we discussed how to work with date and time when using file handling in VB.NET. We covered the syntax, example, output, explanation, use, and important points of working with file date and time in VB.NET. By using the File.GetCreationTime and File.GetLastWriteTime methods, you can get the creation and last write time of a file, respectively.

Published on: