Friends database, using files VB.Net Exercise - Visual Basic Programming Course


 Lesson

File Management

 Exercise

Friends database, using files

Objetive

Expand the "friends database", so that it loads data from file at the beginning of each session (if the file exists) and saves the data to file when the session ends. Therefore, the data entered in a session must be available for the next session.

Code

Imports System
Imports System.IO
Public Class FriendsDatabase
    Structure people
        Public name As String
        Public email As String
        Public address As String
        Public year As UShort
    End Structure

    Public Shared Sub Main()
        Dim total As Integer = 275
        Dim p As people() = New people(total - 1) {}
        Dim amount As Integer = 0
        Dim [option] As Char
        Dim found As Boolean
        Dim textSearch As String
        Dim name As String = "friends.dat"

        If File.Exists(name) Then
            Dim file As StreamReader = File.OpenText(name)
            amount = Convert.ToInt32(file.ReadLine())
            file.ReadLine()

            For i As Integer = 0 To amount - 1

                If i < total Then
                    p(i).name = file.ReadLine()
                    p(i).email = file.ReadLine()
                    p(i).address = file.ReadLine()
                    p(i).year = Convert.ToUInt16(file.ReadLine())
                    file.ReadLine()
                End If
            Next

            file.Close()
        End If

        Do
            Console.WriteLine("1- Add data")
            Console.WriteLine("2- Show")
            Console.WriteLine("3- View all data")
            Console.WriteLine("4- Show between dates")
            Console.WriteLine("5- Show oldest")
            Console.WriteLine("6- Show fields match")
            Console.WriteLine("0- Exit")
            Console.Write("Enter a option: ")
            [option] = Convert.ToChar(Console.ReadLine())

            Select Case [option]
                Case "1"c

                    If amount < total - 1 Then

                        Do
                            Console.Write("Name: ")
                            p(amount).name = Console.ReadLine()
                            If p(amount).name.Length > 40 Then Console.WriteLine("Max 40 letters")
                        Loop While p(amount).name.Length > 40

                        Do
                            Console.Write("Email: ")
                            p(amount).email = Console.ReadLine()
                            If p(amount).email.Length > 30 Then Console.WriteLine("Max 30 letters")
                        Loop While p(amount).email.Length > 30

                        Do
                            Console.Write("Address: ")
                            p(amount).address = Console.ReadLine()
                            If p(amount).address.Length > 150 Then Console.WriteLine("Max 150 letters")
                        Loop While p(amount).address.Length > 150

                        Do
                            Console.Write("Year: ")
                            p(amount).year = Convert.ToUInt16(Console.ReadLine())
                            If p(amount).year < 1850 OrElse p(amount).year > 2100 Then Console.WriteLine("1850-2100")
                        Loop While p(amount).year < 1850 OrElse p(amount).year > 2100

                        amount += 1
                        Console.WriteLine()
                    Else
                        Console.WriteLine("Full")
                    End If

                Case "2"c

                    If amount = 0 Then
                        Console.WriteLine("No data")
                    Else

                        For i As Integer = 0 To amount - 1

                            If p(i).name.Length <= 30 Then
                                Console.WriteLine("{0}: Name = {1}", i + 1, p(i).name)
                            Else
                                Console.WriteLine("{0}: Name = {1}", i + 1, p(i).name.Substring(0, 30) & "...")
                            End If

                            If i Mod 20 = 19 Then Console.ReadLine()
                        Next
                    End If

                Case "3"c
                    Console.Write("Enter the person: ")
                    textSearch = Console.ReadLine()
                    found = False

                    For i As Integer = 0 To amount - 1

                        If textSearch.ToLower() = p(i).name.ToLower() Then
                            found = True
                            Console.WriteLine("{0}: Year = {1}, Email = {2}, Address = {3}", i + 1, p(i).year, p(i).email, p(i).address)
                        End If
                    Next

                    If Not found Then Console.WriteLine("Not exists")
                Case "4"c
                    Console.Write("Enter the first year: ")
                    Dim year1 As Integer = Convert.ToUInt16(Console.ReadLine())
                    Console.Write("Enter the second year: ")
                    Dim year2 As Integer = Convert.ToUInt16(Console.ReadLine())

                    If year1 > year2 Then
                        Dim aux As Integer = year2
                        year2 = year1
                        year1 = aux
                    End If

                    found = False

                    For i As Integer = 0 To amount - 1

                        If p(i).year >= year1 AndAlso p(i).year <= year2 Then
                            Console.Write(p(i).name & " - ")
                            found = True
                        End If
                    Next

                    If Not found Then Console.WriteLine("Not found")
                Case "5"c

                    If amount = 0 Then
                        Console.WriteLine("No data")
                    Else
                        Dim firstYear As Integer = p(0).year
                        found = False

                        For i As Integer = 1 To amount - 1
                            If p(i).year < firstYear Then firstYear = p(i).year
                        Next

                        For i As Integer = 0 To amount - 1
                            Console.WriteLine("{0}: Address = {2}, Year = {3}", i + 1, p(i).name, p(i).address, p(i).year)
                            If Console.ReadLine().ToLower() = "end" Then Exit For
                        Next
                    End If

                Case "0"c
                Case Else
                    Console.WriteLine("Wrong option")
            End Select
        Loop While [option] <> "0"c

        Dim dataFile As StreamWriter = File.CreateText(name)
        dataFile.WriteLine(amount)
        dataFile.WriteLine()

        For i As Integer = 0 To amount - 1
            dataFile.WriteLine(p(i).name)
            dataFile.WriteLine(p(i).email)
            dataFile.WriteLine(p(i).address)
            dataFile.WriteLine(p(i).year)
            dataFile.WriteLine()
        Next

        dataFile.Close()
    End Sub
End Class

More VB.Net Exercises of File Management

 Writing to a text file
Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt"...
 Appending to a text file
Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt". If the file ...
 Display file contents
Create a program to display all the contents of a text file on screen (note: you must use a StreamReader). The name of the file will be entered in the...
 Extended TextToHTML (files)
Expand the TextToHtml class, so that ir can dump it result to a text file. Create a method ToFile, which will receive the name of the file as a parame...
 Logger
Create a class Logger, with a static method Write, which will append a certain text to a file: Logger.Write("myLog.txt", "This text is being logged");...
 More
Create a program which behaves like the Unix command "more": it must display the contents of a text file, and ask the user to press Enter each time th...
 Text replacer
Create a program to replace words in a text file, saving the result into a new file. The file, the word to search and word to replace it with must ...
 Count letters in a file
Create a program to count the amount of times that a certain character is inside a file (of any kind). The file and the letter can be asked to the ...
 Reading a binary file (1: BMP)
Create a Visual Basic (VB.Net) program to check if a BMP image file seems to be correct. It must see if the first two bytes are B and M (ASCII code...
 Writing to a binary file
Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file. Create ...
 Visual Basic (VB.Net) to Java
Create a basic Visual Basic (VB.Net) to Java translator. It must accept a Visual Basic (VB.Net) source files, and create an equivalent Java source ...
 Invert a text file
Create a program to "invert" the contents of a text file: create a file with the same name ending in ".tnv" and containing the same lines as the origi...
 Reading a binay file (2 - GIF)
Create a Visual Basic (VB.Net) program to check if a GIF image file seems to be correct. It must see if the first four bytes are G, I, F, 8. In ...
 Pascal to Visual Basic (VB.Net) translator
Create a basic Pascal to Visual Basic (VB.Net) translator. It will accept program such as: example program; var i: integer; max: integer; b...
 Convert a text file to uppercase
Write a program to read a text file and dump its content to another file, changing the lowercase letters to uppercase. You must deliver only the "....
 Convert any file to uppercase
Write a program to read a file (of any kind) and dump its content to another file, changing the lowercase letters to uppercase. You must deliver on...
 File inverter
Create a program to "invert" a file: create a file with the same name ending in ".inv" and containing the same bytes as the original file but in rever...
 File encrypter
Create a program to encrypt a text file into another text file. It must include the encrypter class you have created previously (in January 17th)...
 Count words
Create a Visual Basic (VB.Net) program to count the amount of words stored in a text file...
 BMP width and height, BinaryReader
Create a Visual Basic (VB.Net) program to display the width and height of a BMP file using a BinaryReader. The structure of the header of a BMP fil...
 TXT to HTML translator
Create a "Text to HTML converter", which will read a source text file and create a HTML file from its contents. For example, if the file contains: Ho...
 Invert binary file V2
Create a program to "invert" a file using a "FileStream". The program should create a file with the same name ending in ".inv" and containing the same...
 BMP width & height, FileStream
Create a Visual Basic (VB.Net) program to display the width and height of a BMP file using a FileStream. Remember the structure of the BMP header: ...
 File copier
Create a program to copy a source file to a destination file. You must use FileStream and a block size of 512 KB. An example usage might be: mycopy...
 MP3 reader
ID3 specifications apply to any file or audiovisual container, but they are primarily used with audio containers. There are three compatible versions ...
 C to Visual Basic (VB.Net) converter
Create a program to convert simple C programs, such as the following one, to Visual Basic (VB.Net): Note: the resulting program must compile correctl...
 File splitter
Create a program to split a file (of any kind) into pieces of a certain size. It must receive the name of the file and the size as parameters. For exa...
 Encrypt a BMP file
Create a program to encrypt/decrypt a BMP image file by changing the "BM" mark in the first two bytes to "MB" and vice versa. Use the advanced File...
 CSV converter
The CSV ("Comma Separated Values") is an exchange format used by many spreadsheet and database management systems. It consists of a series of comma-se...
 File comparer
Create a Visual Basic (VB.Net) program to tell if two files (of any kind) are identical (have the same content)....
 Display BPM on console
The Netpbm format is a family of image file formats designed with simplicity in mind, rather than small size. They can represent color, grayscale, or ...
 PCX width and height
Create a program that checks if a file is a PCX image and, if so, displays its width and height using the following specification: What is the PCX ...
 Extract text from a binary file
Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters s...
 Visual Basic (VB.Net) to Pascal converter
Create a program that converts simple Visual Basic (VB.Net) programs, such as the following one, to the Pascal language....
 Dump
Create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should p...
 DBF extractor
Create a program that displays the list of fields stored in a DBF file. The DBF format is used by the old dBase database manager and is still suppo...
 Text censorer
Create a program to censor text files. It should read a text file and dump its results to a new text file, replacing certain words with "[CENSORED]". ...
 SQL to text
You must create a Visual Basic (VB.Net) program that is capable of parsing SQL INSERT commands and extracting their data into separate lines of text, ...
 PGM viewer
The PGM format is one of the versions of NetPBM image formats. Specifically, it is the variant capable of handling images in shades of gray. Its he...
 Display BMP on console V2
Create a program to display a 72x24 BMP file on the console. You must use the information in the BMP header (refer to the exercise of Feb. 7th). Pay a...


Juan A. Ripoll - Systems Tutorials and Programming Courses © 2024 All rights reserved.  Legal Conditions.