Home

Details on Files

 

File Information

 

Introduction

In its high level of support for file processing, the .NET Framework provides the FileInfo class. This class is equipped to handle all types of file-related operations including creating, copying, moving, renaming, or deleting a file. FileInfo is based on the FileSystemInfo class that provides information on characteristics of a file.

To assist you with finding information about a file, the FileSystem class from the My object is equipped with a method named GetFileInfo.

 

Practical LearningPractical Learning: Introducing File Information

  1. Start Microsoft Visual Basic and create a new Windows Application named WattsALoan1
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type WattsALoan.vb and press Enter
  4. Design the form as follows:
     
    Watts A Loan
    Control Name Text
    Label   Acnt #:
    Label   Customer Name:
    Label   Customer:
    TextBox txtAccountNumber  
    TextBox txtCustomerName  
    Label   Empl #:
    Label   Employee Name:
    Label   Prepared By:
    TextBox txtEmployeeNumber  
    TextBox txtEmployeeName  
    Button btnNewEmployee  
    Label   Loan Amount:
    TextBox txtLoanAmount TextAlign: Right
    Label   Interest Rate:
    TextBox txtInterestRate TextAlign: Right
    Label   %
    Label   Periods
    TextBox   txtPeriods
    TextAlign: Right
    Button btnCalculate Calculate
    Label   Monthly Payment:
    TextBox txtMonthlyPayment  
    Button btnClose Close
  5. Right-click the form and click View Code
  6. Just above the Public Class line, import the System.IO namespace:
     
    Imports System.IO
    
    Public Class WattsALoan
  7. In the Class Name combo box, select btnCalculate
  8. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCalculate_Click(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles btnCalculate.Click
            Dim LoanAmount As Double
            Dim InterestRate As Double
            Dim Periods As Double
            Dim MonthlyPayment As Double
    
            Try
                LoanAmount = CDbl(txtLoanAmount.Text)
            Catch ex As Exception
                MsgBox("Invalid Loan Amount")
            End Try
    
            Try
                InterestRate = CDbl(txtInterestRate.Text)
            Catch ex As Exception
    
                MsgBox("Invalid Interest Rate")
            End Try
    
            Try
                Periods = CDbl(txtPeriods.Text)
            Catch ex As Exception
                MsgBox("Invalid Periods Value")
            End Try
    
            MonthlyPayment = Pmt(InterestRate / 12 / 100, _
                                 Periods, -LoanAmount, 0, _
                                 DueDate.BegOfPeriod)
            txtMonthlyPayment.Text = FormatCurrency(MonthlyPayment)
    End Sub
  9. In the Class Name combo box, select btnClose
  10. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  11. Save the file

File Initialization

The FileInfo class is equipped with one constructor whose syntax is:

Public Sub New(fileName As String)

This constructor takes as argument the name of a file or its complete path. If you provide only the name of the file, the compiler would consider the same directory of its project.

As mentioned previously, to get information about a file, you can call the GetFileInfo() method of the FileSystem class from the My object. Its syntax is:

Public Shared Function GetFileInfo(file As String) As FileInfo

This shared method returns a FileInfo object. Here is an example of calling it:

Imports System.IO

Public Class Exercise

    Private Filename As String

    Private Sub btnFileInformation_Click(ByVal sender As System.Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnFileInformation.Click
        Dim PeopleInformation As FileInfo

        PeopleInformation = My.Computer.FileSystem.GetFileInfo(Filename)
    End Sub
End Class

After calling this method, you can then use its returned value to get the information you want about the file.

Practical LearningPractical Learning: Initializing a File

  1. In the Class Name combo box, select (WattsALoan Events)
  2. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub WattsALoan_Load(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Me.Load
            Dim Filename As String = "Employees.wal"
            Dim EmployeeInformation As FileInfo = _
                    My.Computer.FileSystem.GetFileInfo(Filename)
    End Sub
  3. Save the file

File Creation

The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether it exists already or it would be created. Based on this, if you execute an application that has only a FileInfo object created using the constructor as done above, nothing would happen.

To create a file, you have various alternatives. If you want to create one without writing anything in it, which implies creating an empty file, you can call the FileInfo.Create() method. Its syntax is:

Public Function Create As FileStream

This method simply creates an empty file. Here is an example of calling it:

Private Sub btnFileInformation_Click(ByVal sender As System.Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnFileInformation.Click
        Dim PeopleInfo As FileInfo = New FileInfo("People.txt")
        PeopleInfo.Create()
End Sub

The FileInfo.Create() method returns a FileStream object. You can use this returned value to write any type of value into the file, including text. If you want to create a file that contains text, an alternative is to call the FileInfo.CreateText() method. Its syntax is:

Public Function CreateText As StreamWriter

This method returns a StreamWriter object. You can use this returned object to write text to the file.

File Existence

When you call the FileInfo.Create() or the FileInfo.CreateText() method, if the file passed as argument, or as the file in the path of the argument, exists already, it would be deleted and a new one would be created with the same name. This can cause an important file to be deleted. Therefore, before creating a file, you may need to check whether it exists already. To do this, you can check the value of the Boolean FileInfo.Exists property. This property holds a True value if the file exists already and it holds a False value if the file does not yet exist or it does not exist in the path. Here is an example of calling it:

Private Sub btnFileInformation_Click(ByVal sender As System.Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnFileInformation.Click
        Dim Filename As String
        Dim PeopleInformation As FileInfo

        Filename = "Student12.std"
        PeopleInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If PeopleInformation.Exists = True Then
            MsgBox("The file exists already")
        Else
            MsgBox("Unknown file")
        End If
End Sub

Practical LearningPractical Learning: Creating a Text File

  1. Change the Load event of the form as follows:
     
    Private Sub WattsALoan_Load(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Me.Load
            Dim EmployeeWriter As StreamWriter
            Dim Filename As String = "Employees.wal"
            Dim EmployeeInformation As FileInfo = _
                    My.Computer.FileSystem.GetFileInfo(Filename)
    
            ' If the employees file was not created already,
            ' then create it
            If Not EmployeeInformation.Exists Then
                EmployeeWriter = EmployeeInformation.CreateText()
            End If
    End Sub
  2. Save the file

Writing to a File

As mentioned earlier, the FileInfo.Create() and the FileInfo.CreateText() methods can be used to create a file but they not write values to the file. To write values in the file, each method returns an appropriate object. The  FileInfo.Create() method returns FileStream object. You can use this to specify the type of operation that would be allowed on the file. To write normal text to a file, you can first call the FileInfo.CreateText() method that returns a StreamWriter object. Here is an example:

Private Sub btnSave_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnSave.Click
        Dim Filename As String
        Dim StudentsWriter As StreamWriter
        Dim StudentInformation As FileInfo

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)
        StudentsWriter = StudentInformation.CreateText()

        Try
            StudentsWriter.WriteLine(txtFirstName.Text)
            StudentsWriter.WriteLine(txtLastName.Text)
            StudentsWriter.WriteLine(cbxGenders.SelectedIndex)

            txtFirstName.Text = ""
            txtLastName.Text = ""
            cbxGenders.SelectedIndex = 2
        Finally
            StudentsWriter.Close()
        End Try
End Sub

As an alternative to Create() or CreateText(), if you want to create a file that can only be written to, you can call the FileInfo.OpenWrite() method. Its syntax is:

Public Function OpenWrite As FileStream

This method returns a FileStream that you can then use to write values into the file.

Practical LearningPractical Learning: Writing to a Text File

  1. Change the Load event of the form as follows:
     
    Private Sub WattsALoan_Load(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Me.Load
            Dim EmployeeWriter As StreamWriter
            Dim Filename As String = "Employees.wal"
            Dim EmployeeInformation As FileInfo = _
                    My.Computer.FileSystem.GetFileInfo(Filename)
    
            ' If the employees file was not created already,
            ' then create it
            If Not EmployeeInformation.Exists Then
                EmployeeWriter = EmployeeInformation.CreateText()
    
                ' And create a John Doe employee
                Try
                    EmployeeWriter.WriteLine("00-000")
                    EmployeeWriter.WriteLine("John Doe")
                Finally
                    EmployeeWriter.Close()
                End Try
            End If
    End Sub
  2. Save the file

Appending to a File

You may have created a text-based file and written to it. If you open such a file and find out that a piece of information is missing, you can add that information to the end of the file. To do this, you can call the FileInfo.AppenText() method. Its syntax is:

Public Function AppendText As StreamWriter

When calling this method, you can retrieve the StreamWriter object that it returns, then use that object to add new information to the file.

Practical LearningPractical Learning: Writing to a Text File

  1. To create a new form, on the main menu, click Project -> Add Windows Form...
  2. In the Templates list, make sure Windows Form is selected. Set the Name to NewEmployee and click Add
  3. Design the form as follows:
     
    Control Text Name
    Label Employee #:
    TextBox txtEmployeeNumber
    Label Employee Name:
    TextBox txtEmployeeName
    Button Create btnCreate
    Button Close btnClose
  4. Right-click the form and click View Code
  5. In the top section of the file, just above the Public Class line, import the System.IO namespace:
     
    Imports System.IO
    
    Public Class NewEmployee
    
    End Class
  6. In the Class Name combo box, select btnCreate
  7. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCreate_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles btnCreate.Click
            Dim Filename As String = "Employees.wal"
            Dim EmployeeInformation As FileInfo = New FileInfo(Filename)
            Dim EmployeeWriter As StreamWriter
    
            ' Normally, we should have the file already but just in case...
            If Not EmployeeInformation.Exists Then
                EmployeeWriter = EmployeeInformation.CreateText()
            Else ' If the file exists already, then we will only add to it
                EmployeeWriter = EmployeeInformation.AppendText()
            End If
    
            Try
                EmployeeWriter.WriteLine(txtEmployeeNumber.Text)
                EmployeeWriter.WriteLine(txtEmployeeName.Text)
            Finally
                EmployeeWriter.Close()
            End Try
    
            txtEmployeeNumber.Text = ""
            txtEmployeeName.Text = ""
            txtEmployeeNumber.Focus()
    End Sub
  8. In the Class Name combo box, select btnClose
  9. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Close()
    End Sub
  10. In the Solution Explorer, right-click WattsALoan.vb and click View Code
  11. In the Class Name combo box, select btnNewEmployee
  12. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewEmployee_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnNewEmployee.Click
            Dim FormEmployee As NewEmployee = New NewEmployee()
    
            FormEmployee.ShowDialog()
    End Sub
  13. In the Class Name combo box, select txtEmployeeNumber
  14. In the Method Name combo box, select Leave
  15. Implement the event as follows:
     
    Private Sub txtEmployeeNumber_Leave(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles txtEmployeeNumber.Leave
            Dim Found As Boolean
            Dim Filename As String
            Dim EmployeeReader As StreamReader
            Dim EmployeeInformation As FileInfo
            Dim EmployeeNumber As String, EmployeeName As String
    
            Filename = "Employees.wal"
            EmployeeInformation = My.Computer.FileSystem.GetFileInfo(Filename)
    
            If EmployeeInformation.Exists Then
    
                If txtEmployeeNumber.Text = "" Then
                    txtEmployeeName.Text = ""
                    Exit Sub
                Else
                    EmployeeReader = EmployeeInformation.OpenText()
    
                    Try
    
                        Do
                            EmployeeNumber = EmployeeReader.ReadLine()
    
                            If EmployeeNumber = txtEmployeeNumber.Text Then
    
                                EmployeeName = EmployeeReader.ReadLine()
                                txtEmployeeName.Text = EmployeeName
                                Found = True
                            End If
                        Loop While EmployeeReader.Peek() >= 0
    
                        ' When the application has finished checking the file
                        ' if there was no employee with that number, let the user know
                        If Found = False Then
    
                            MsgBox("No employee with that number was found")
                            txtEmployeeName.Text = ""
                            txtEmployeeNumber.Focus()
                        End If
                    Finally
                        EmployeeReader.Close()
                    End Try
                End If
            End If
    End Sub
  16. Execute the application to test it
  17. First create a few employees as follows:
     
    Employee # Employee Name
    42-806 Patricia Katts
    75-148 Helene Mukoko
    36-222 Frank Leandro
    42-808 Gertrude Monay
  18. Process a loan
     
    Watts A Loan
  19. Close the application

Reading from a File

As opposed to writing to a file, you can read from it. To support this, the FileInfo class is equipped with a method named OpenText(). Its syntax is:

Public Function OpenText As StreamReader

This method returns a StreamReader object. You can then use this object to read the lines of a text file. Here is an example:

Private Sub btnOpen_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click
        Dim Filename As String
        Dim StudentsReader As StreamReader
        Dim StudentInformation As FileInfo

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)
        StudentsReader = StudentInformation.OpenText

        Try
            txtFirstName.Text = StudentsReader.ReadLine
            txtLastName.Text = StudentsReader.ReadLine
            cbxGenders.SelectedIndex = CInt(StudentsReader.ReadLine)

        Finally
            StudentsReader.Close()
        End Try
End Sub

If you want to open a file that can only be read from, you can call the FileInfo.OpenRead() method. Its syntax is:

Public Function OpenRead As FileStream

This method returns a FileStream that you can then use to read values from the file.

Routine Operations on Files

 

Opening a File

As opposed to creating a file, probably the second most regular operation performed on a file consists of opening it to read or explore its contents. To support opening a file, the FileInfo class is equipped with the Open() method that is overloaded with three versions. Their syntaxes are:

Public Function Open ( _
	mode As FileMode _
) As FileStream
Public Function Open ( _
	mode As FileMode, _
	access As FileAccess _
) As FileStream
Public Function Open ( _
	mode As FileMode, _
	access As FileAccess, _
	share As FileShare _
) As FileStream

You can select one of these methods, depending on how you want to open the file, using the options for file mode, file access, and file sharing. Each version of this method returns a FileStream object that you can then use to process the file. After opening the file, you can then read or use its content.

Deleting a File

If you have an existing file you don't need anymore, you can delete it. This operation can be performed by calling the FileInfo.Delete() method. Its syntax is:

Public Overrides Sub Delete

Here is an example:

Private Sub btnDelete_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnDelete.Click
        Dim Filename As String
        Dim StudentInformation As FileInfo

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If PeopleInformation.Exists = True Then
            StudentInformation.Delete()
        Else
            MsgBox("Unknown file")
        End If
End Sub

Copying a File

You can make a copy of a file from one directory to another. To do this, you can call the FileInfo.CopyTo() method that is overloaded with two versions. One of the versions has the following syntax:

public FileInfo CopyTo(string destFileName)

When calling this method, specify the path or directory that will be the destination of the copied file. Here is an example:

Private Sub btnCopy_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnCopy.Click
        Dim Filename As String
        Dim StudentInformation As FileInfo
        Dim MyDocuments As String = _
        	Environment.GetFolderPath(Environment.SpecialFolder.Personal)

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If StudentInformation.Exists = True Then
            StudentInformation.CopyTo(MyDocuments & "\Federal.txt")
        Else
            MsgBox("Unknown file")
        End If
End Sub

In this example, a file named Reality.txt in the directory of the project would be retrieved and its content would be applied to a new file named Federal.txt created in the My Documents folder of the current user.

When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite the target file. To do this, you can use the second version of this method. Its syntax is:

Public Function CopyTo(destFileName As String, overwrite As Boolean) As FileInfo

The first argument is the same as that of the first version of the method. The second argument specifies what action to take if the file exists already in the target directory. If you want to overwrite it, pass the second argument as true; otherwise, pass it as false. Here is an example:

Private Sub btnCopy_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnCopy.Click
        Dim Filename As String
        Dim StudentInformation As FileInfo
        Dim MyDocuments As String = _
        Environment.GetFolderPath(Environment.SpecialFolder.Personal)

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If StudentInformation.Exists = True Then
            StudentInformation.CopyTo(MyDocuments & "\Federal.txt", True)
        Else
            MsgBox("Unknown file")
        End If
End Sub

Moving a File

If you copy a file from one directory to another, you would have two copies of the same file or the same contents in two files. Instead of copying, if you want, you can simply move a file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its syntax is:

Public Sub MoveTo(destFileName As String)

The argument to this method is the same as that of the CopyTo() method. After executing this method, the FileInfo object would be moved to the destFileName path.

Here is an example:

Private Sub btnMove_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnMove.Click
        Dim Filename As String
        Dim StudentInformation As FileInfo
        Dim MyDocuments As String = _
        Environment.GetFolderPath(Environment.SpecialFolder.Personal)

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If StudentInformation.Exists = True Then
            StudentInformation.MoveTo(MyDocuments & "\Federal.txt")
        Else
            MsgBox("Unknown file")
        End If
End Sub

Characteristics of a File

 

The Date and Time a File Was Created 

After a file has been created, the operating system makes a note of the date and the time the file was created. This information can be valuable in other operations such as search routines. You too are allowed to change this date and time values to those you prefer.

As mentioned already, the OS makes sure to keep track of the date and time a file was created. To find out what those date and time values are, you can access the get accessor of the FileSystemInfo.CreationTime property, which is of type DateTime. Here is an example of using it:

Private Sub btnCreationDate_Click(ByVal sender As System.Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles btnCreationDate.Click
        Dim Filename As String
        Dim FileCreationTime As DateTime
        Dim StudentInformation As FileInfo

        Filename = "Student1.std"
        StudentInformation = My.Computer.FileSystem.GetFileInfo(Filename)

        If StudentInformation.Exists = True Then
            FileCreationTime = StudentInformation.CreationTime
            MsgBox(FormatDateTime(FileCreationTime, DateFormat.LongDate))
        Else
            MsgBox("Unknown file")
        End If

End Sub

Of course, by formatting the value, you can get only either the date or only the time.

If you don't like the date, the time, or both, that the OS would have set when the file was created, you can change them. To change one or both of these values, you can assign a desired DateTime object to the set accessor of the FileSystemInfo.CreationTime property.

The Date and Time a File Was Last Accessed 

Many applications allow a user to open an existing file and to modify it. When people work in a team or when a particular file is regularly opened, at one particular time, you may want to know the date and time that the file was last accessed. To get this information, you can access the FileSystemInfo.LastAccessTime property, which is of type DateTime.

If you are interested to know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property, which is of type DateTime.

The Name of a File

The operating system requires that each file have a name. In fact, the name must be specified when creating a file. This allows the OS to catalogue the computer files. This also allows you to locate or identify a particular file you need.

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. Here is an example:

MsgBox("The name of this file is: \"+ & fleLoan.Name & "\"")

This string simply identifies a file.

The Extension of a File

With the advent of Windows 95 and later, the user doesn't have to specify the extension of a file when creating it. Because of the type of confusion that this can lead to, most applications assist the user with this detail. Some applications allow the user to choose among various extensions. For example, using Notepad, a user can open a text, a PHP, a script, or an HTML file.

When you access a file or when the user opens one, to know the extension of the file, you can access the value of the FileSystemInfo.Extension property. Here is an example:

MsgBox("File Extension: " & fleLoan.Extension)

The Size of a File

One of the routine operations the operating system performs consists of calculating the size of files it holds. This information is provided in terms of bits, kilobits, or kilobytes. To get the size of a file, the FileInfo class is quipped with the Length property. Here is an example of accessing it:

MsgBox("File Size: " & fleLoan.Length.ToString())

The Path to a File

Besides its name, a file must be located somewhere. The location of a file is referred to as its path or directory. The FileInfo class represents this path as the DirectoryName property. Therefore, if a file has already been created, to get its path, you can access the value of the FileInfo.DirectoryName property.

Besides the FileInfo.Directoryname, to know the full path to a file, you can access its FileSystemInfo.FullName property.

The Attributes of a File

Attributes are characteristics that apply to a file, defining what can be done or must be disallowed on it. The Attributes are primarily defined by, and in, the operating system, mostly when a file is created. When the user accesses or opens a file, to get its attributes, you can access the value of its FileSystemInfo.Attributes property. This property produces a FileAttributes object.

When you create or access a file, you can specify or change some of the attributes. To do this, you can create a FileAttributes object and assign it to the FileSystemInfo.Attributes property.

FileAttributes is an enumeration with the following members: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.

Directories

 

Introduction

A directory is a section of a medium (floppy disc, flash drive, hard drive, CD, DVD, etc) used to delimit a group of files. Because it is a "physical" area, it can handle operations not available on files. In fact, there are many fundamental differences between both:

  • A file is used to contain data. A directory doesn't contain data
  • A directory can contain one or more files and not vice-versa
  • A directory can contain other directories
  • A file can be moved from one directory to another. This operation is not possible vice-versa since a file cannot contain a directory

The similarities of both types are:

  • A directory or a file can be created. One of the restrictions is that two files cannot have the same name inside of the same directory. Two directories cannot have the same name inside of the same parent directory.
  • A directory or a file can be renamed. If a directory is renamed, the "path" of its file(s) changes
  • A directory or a file can be deleted. If a directory is deleted, its files are deleted also
  • A directory or a file can be moved. If a directory moves, it "carries" all of its files to the new location
  • A directory or a file can be copied. A file can be copied from one directory to another. If a directory is copied to a new location, all of its files are also copied to the new location

Practical LearningPractical Learning: Introducing Directories

  1. Create a new Windows Application, named WattsALoan2
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type WattsALoan.vb and press Enter
  4. Design the form as follows:
     
    Watts' A Loan
    Control Name Text
    Label   If this is a new loan, enter a new account number and the name of the customer who is requesting the loan
    Label   To open a previously prepared loan, enter its account number and press Tab
    Label   Acnt #:
    Label   Customer Name:
    Label   Customer:
    TextBox txtAccountNumber  
    TextBox txtCustomerName  
    Label   Empl #:
    Label   Employee Name:
    Label   Prepared By:
    TextBox txtEmployeeNumber  
    TextBox txtEmployeeName  
    Button btnNewEmployee  
    Button btnNewCustomer  
    Label   Loan Amount:
    TextBox txtLoanAmount  
    Label   Interest Rate:
    TextBox txtInterestRate  
    Label   %
    Label   Periods
    TextBox   txtPeriods
    Button btnCalculate Calculate
    Label   Monthly Payment:
    TextBox txtMonthlyPayment  
    Button btnClose Close
  5. Double-click the Calculate button and implement its event as follows:
     
    Imports System.IO
    
    Public Class WattsALoan
    
        Private Sub btnCalculate_Click(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles btnCalculate.Click
            Dim LoanAmount As Double
            Dim InterestRate As Double
            Dim Periods As Double
            Dim MonthlyPayment As Double
    
            Try
                LoanAmount = CDbl(txtLoanAmount.Text)
            Catch ex As Exception
                MsgBox("Invalid Loan Amount")
            End Try
    
            Try
                InterestRate = CDbl(txtInterestRate.Text)
            Catch ex As Exception
    
                MsgBox("Invalid Interest Rate")
            End Try
    
            Try
                Periods = CDbl(txtPeriods.Text)
            Catch ex As Exception
                MsgBox("Invalid Periods Value")
            End Try
    
            MonthlyPayment = Pmt(InterestRate / 12 / 100, _
                                 Periods, -LoanAmount, 0, _
                                 DueDate.BegOfPeriod)
            txtMonthlyPayment.Text = FormatCurrency(MonthlyPayment)
        End Sub
    End Class
  6. In the Class Name combo box, select btnClose
  7. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            End
    End Sub
  8. To create a new form, on the main menu, click Project -> Add Windows Form...
  9. In the Templates list, make sure Windows Form is selected.
    Set the Name to NewEmployee and click Add
  10. Design the form as follows:
     
    Control Text Name
    Label Employee #:
    TextBox txtEmployeeNumber
    Label Employee Name:
    TextBox txtEmployeeName
    Button Create btnCreate
    Button Close btnClose
  11. Double-click the Close button
  12. Implement the event as follows:
     
    Imports System.IO
    
    Public Class NewEmployee
    
        Private Sub btnClose_Click(ByVal sender As System.Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Close()
        End Sub
    End Class
  13. In the Solution Explorer, right-click WattsALoan.vb and click View Code
  14. In the Class Name combo box, select btnNewEmployee
  15. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewEmployee_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnNewEmployee.Click
            Dim FormEmployee As NewEmployee = New NewEmployee()
    
            FormEmployee.ShowDialog()
    End Sub
  16. Save the file

Directory Creation

Before using a directory, you must first have it. You can use an existing directory if the operating system or someone else had already created one. You can also create a new directory. Directories are created and managed by various classes but the fundamental class is called Directory. Directory is a static class. All of its methods are static, which means you will never need to declare an instance of the Directory class in order to use it.

Besides the Directory class, additional operations of folders and sub-folders can be performed using the DirectoryInfo class.

To create a directory, you can call the CreateDirectory() method of the Directory class. This method is available in two versions. One of the versions uses the following syntax:

Public Shared Function CreateDirectory(path As String) As DirectoryInfo

This method takes as argument the (complete) path of the desired directory. Here is an example:

E:\Programs\Business Orders\Customer Information

When this method is called:

  1. It first checks the parent drive, in this case E.
    If the drive doesn't exist, because this method cannot create a drive, the compiler would throw a DirectoryNotFoundException exception
  2. If the drive (in this case E) exists, the compiler moves to the first directory part of the path; in this case this would be the Programs folder in the E drive.
    If the folder doesn't exist, the compiler would create it. If that first director doesn't exist, this means that the other directory(ies), if any, under the first don't exist. So, the compiler would create it/them
  3. If the first directory exists and if there is no other directory under that directory, the compiler would stop and would not do anything further.
  4. If the directory exists and there is a sub-directory specified under it, the compiler would check the existence of that directory.
    If the sub-directory exists, the compiler would not do anything further and would stop.
    If the sub-directory doesn't exist, the compiler would create it
  5. The compiler would repeat step 4 until the end of the specified path

The Directory.CreateDirectory() method returns a DirectoryInfo object that you can use as you see fit.

Practical LearningPractical Learning: Creating a Directory

  1. In the Class Name combo box, select (WattsALoan Events)
  2. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub WattsALoan_Load(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles Me.Load
            Dim Folder As String
            Dim EmployeeWriter As StreamWriter
            Dim Filename As String = "Employees.wal"
            Dim EmployeeInformation As FileInfo = _
                    My.Computer.FileSystem.GetFileInfo(Filename)
    
            Folder = "C:\Watts A Loan"
    
            If Not Directory.Exists(Folder) Then
                Directory.CreateDirectory(Folder)
    
                Dim strFilename As String = Folder & "\Employees.wal"
    
                Dim fiEmployees As FileInfo = New FileInfo(strFilename)
    
                ' If the employees file was not created already,
                ' then create it
                If Not EmployeeInformation.Exists Then
                    EmployeeWriter = EmployeeInformation.CreateText()
    
                    ' And create a John Doe employee
                    Try
                        EmployeeWriter.WriteLine("00-000")
                        EmployeeWriter.WriteLine("John Doe")
                    Finally
                        EmployeeWriter.Close()
                    End Try
                End If
            End If
    End Sub
  3. In the Solution Explorer, right-click NewEmployee and click View Code
  4. In the Class Name combo box, select btnCreate
  5. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCreate_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles btnCreate.Click
            Dim Filename As String = "C:\Watts A Loan\Employees.wal"
            Dim EmployeeInformation As FileInfo
            Dim EmployeeWriter As StreamWriter
    
            EmployeeInformation = My.Computer.FileSystem.GetFileInfo(Filename)
    
            ' Normally, we should have the file already but just in case...
            If Not EmployeeInformation.Exists Then
                EmployeeWriter = EmployeeInformation.CreateText()
            Else ' If the file exists already, then we will only add to it
                EmployeeWriter = EmployeeInformation.AppendText()
            End If
    
            Try
                EmployeeWriter.WriteLine(txtEmployeeNumber.Text)
                EmployeeWriter.WriteLine(txtEmployeeName.Text)
            Finally
                EmployeeWriter.Close()
            End Try
    
            txtEmployeeNumber.Text = ""
            txtEmployeeName.Text = ""
            txtEmployeeNumber.Focus()
    End Sub
  6. Click the WattsALoan.vb [Design] tab

Checking for a Directory Existence

Before using or creating a directory, you can first check if it exists. This is because, if a directory already exists in the location where you want to create it, you would be prevented from creating one with the same name. In the same way, if you just decide to directly use a directory that doesn't exist, the operation you want to perform may fail because the directory would not be found.

To check whether a directory exists or not, you can call the Directory.Exists() Boolean static method. Its syntax is:

Public Shared Function Exists(path As String) As Boolean

This method receives the (complete) path of the directory. If the path exists, the method returns true. If the directory doesn't exist, the method returns false.

Locating a File

One of the most routine operations performed in a directory consists of looking for a file. Microsoft Windows operating systems and the user's intuition have different ways of addressing this issue. The .NET Framework also provides its own means of performing this operation, through various techniques. You can start by checking the sub-directories and files inside of a main directory.

To look for files in a directory, the DirectoryInfo class can assist you with its GetFiles() method, which is overloaded with three versions.

Practical LearningPractical Learning: Using Directories and Files

  1. In the Class Name combo box, select txtAccountNumber
  2. In the Method Name combo box, select Leave and implement the event as follows:
     
    Private Sub txtAccountNumber_Leave(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles txtAccountNumber.Leave
            Dim Filename As String
            Dim LoanPath As String
            Dim FileFullname As String
            Dim ListOfLoans() As FileInfo
            Dim LoanReader As StreamReader
            Dim LoanFolder As DirectoryInfo
            Dim LoanInformation As FileInfo
            Dim Found As Boolean
    
            Found = False
            LoanPath = "C:\Watts A Loan"
    
            LoanFolder = New DirectoryInfo(LoanPath)
            ListOfLoans = LoanFolder.GetFiles("*", _
                                SearchOption.AllDirectories)
            Filename = txtAccountNumber.Text & ".wal"
            FileFullname = LoanPath & "none.wal"
    
            For Each fle As FileInfo In ListOfLoans
                If fle.Name = Filename Then
                    Found = True
                    FileFullname = fle.FullName
                End If
            Next
    
            If Found = True Then
    
                LoanInformation = My.Computer.FileSystem.GetFileInfo(Filename)
                LoanReader = LoanInformation.OpenText
                
                Try
                    txtAccountNumber.Text = LoanReader.ReadLine
                    txtCustomerName.Text = LoanReader.ReadLine
                    txtEmployeeNumber.Text = LoanReader.ReadLine
                    txtEmployeeName.Text = LoanReader.ReadLine
                    txtLoanAmount.Text = LoanReader.ReadLine
                    txtInterestRate.Text = LoanReader.ReadLine
                    txtPeriods.Text = LoanReader.ReadLine
                    txtMonthlyPayment.Text = LoanReader.ReadLine
                Finally
                    LoanReader.Close()
                End Try
            End If
    End Sub
  3. In the Class Name combo box, select txtEmployeeNumber
  4. In the Method Name combo box, select click Leave and implement the event as follows:
     
    Private Sub txtAccountNumber_Leave(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles txtAccountNumber.Leave
            Dim Filename As String
            Dim LoanPath As String
            Dim FileFullname As String
            Dim ListOfLoans() As FileInfo
            Dim LoanReader As StreamReader
            Dim LoanFolder As DirectoryInfo
            Dim LoanInformation As FileInfo
            Dim Found As Boolean
    
            Found = False
            LoanPath = "C:\Watts A Loan"
    
            LoanFolder = New DirectoryInfo(LoanPath)
            ListOfLoans = LoanFolder.GetFiles("*", _
                                SearchOption.AllDirectories)
            Filename = txtAccountNumber.Text & ".wal"
            FileFullname = LoanPath & "none.wal"
    
            For Each fle As FileInfo In ListOfLoans
                If fle.Name = Filename Then
                    Found = True
                    FileFullname = fle.FullName
                End If
            Next
    
            If Found = True Then
    
                LoanInformation = My.Computer.FileSystem.GetFileInfo(FileFullname)
                MsgBox(LoanInformation.FullName)
                LoanReader = LoanInformation.OpenText
    
                Try
                    txtAccountNumber.Text = LoanReader.ReadLine
                    txtCustomerName.Text = LoanReader.ReadLine
                    txtEmployeeNumber.Text = LoanReader.ReadLine
                    txtEmployeeName.Text = LoanReader.ReadLine
                    txtLoanAmount.Text = LoanReader.ReadLine
                    txtInterestRate.Text = LoanReader.ReadLine
                    txtPeriods.Text = LoanReader.ReadLine
                    txtMonthlyPayment.Text = LoanReader.ReadLine
                Finally
                    LoanReader.Close()
                End Try
            End If
    End Sub
  5. In the Class Name combo box, select btnSave
  6. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnSave_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnSave.Click
            Dim LoanPath As String
            Dim LoanWriter As StreamWriter
    
            LoanPath = "C:\Watts A Loan\" & txtAccountNumber.Text & ".wal"
            LoanWriter = My.Computer.FileSystem.OpenTextFileWriter(LoanPath, False)
    
            Try
                LoanWriter.WriteLine(txtAccountNumber.Text)
                LoanWriter.WriteLine(txtCustomerName.Text)
                LoanWriter.WriteLine(txtEmployeeNumber.Text)
                LoanWriter.WriteLine(txtEmployeeName.Text)
                LoanWriter.WriteLine(txtLoanAmount.Text)
                LoanWriter.WriteLine(txtInterestRate.Text)
                LoanWriter.WriteLine(txtPeriods.Text)
                LoanWriter.WriteLine(txtMonthlyPayment.Text)
    
                txtAccountNumber.Text = ""
                txtCustomerName.Text = ""
                txtEmployeeNumber.Text = ""
                txtEmployeeName.Text = ""
                txtLoanAmount.Text = ""
                txtInterestRate.Text = ""
                txtPeriods.Text = ""
                txtMonthlyPayment.Text = ""
                txtAccountNumber.Focus()
            Finally
                LoanWriter.Close()
            End Try
    End Sub
  7. Execute the application to test it
  8. First create a few employees as follows:
     
    Employee # Employee Name
    42-806 Patricia Katts
    75-148 Helene Mukoko
    36-222 Frank Leandro
    42-808 Gertrude Monay
  9. Process a few loans
     
    Watts A Loan - Loan Preparation
     
    Watts A Loan - Loan Result
  10. Close the application

Exercises

 

Watts A Loan

  1. Open the WattsALoan1 application from this lesson
  2. Provide tool tips for the various controls
  3. Provide help to the application
  4. Open the WattsALoan2 application from this lesson
  5. Provide tool tips for the various controls
  6. Provide help to the application

Clarksville Ice Cream

  1. Open the ClarskvilleIceCream application from the previous lesson
  2. In the sections that deal with file processing add a finally block
  3. Write your code to handle the FileNotFoundException exception

 

 

Previous Copyright 2008 Yevol Next