To demonstrate how to read and write binary files, I’ve created a Visual Basic console application. I’m going to create two subroutines-the first is
going to write the current time to a binary file, and the second is going to read it in from the console. First, I’ll create the structure for them.
Now, I’m going to need to create a FileStream object in order to create the BinaryWriter instance, and doing that requires the System.IO
namespace that I’m adding now. Now, I’ll create the FileStream object by specifying the filename and the parameter that specifying we’re going to
create the file. Sorry, I typed using instead of imports.
Now, I’m going to create a BinaryWriter object by specifying the FileStream I just created as part of the constructor. That provides the filename to the
BinaryWriter. Now, I’m ready to actually write the DateTime to
the binary file using the BinaryWriter.Write method. Notice, of all of the different types that I can give to the Write method, none of these
support the DateTime parameter. All I can do is to write the house and minutes separately, and then read them back separately. Those parameters
are each integers. Now that I’ve written the data I am going to close
the BinaryWriter and the FileStream objects.
Now I’m ready to create the ShowPreviousTime subroutine. I need to create a FileStream object exactly as I did when creating the BinaryWriter.
The BinaryReader class takes basically the same parameters, a FileStream object, except this time I’m going to specify FileMode.Open because I’m
not going to be creating a file--I’m only trying to read the file.
Now I’m going to create the BinaryReader and specify the FileStream object for it.
Now I’m going to read in the objects in exactly the same order as I wrote them. I’m going to use exactly the same types, too. So, I’m going to
create a string and use that to concatenate the time in a readable format. I’m reading them in as Int32s and adding a colon in between them.
Now that I’ve concatenated those into a readable time, I’m going to send it to the console with Console.WriteLine.
One last thing to do—call those subroutines from the Main method. Then, I’ll call Console.ReadKey to make the console wait for me so we can see
the display. Now, I’ll run it.
So, you can probably see my mistake there—I’m too accustomed to using C#. I need to use ampersands here instead of plus symbols.
And, there we go—the time is 5:44.