Home

File Information: 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.

If you have a text-based file and want to directly read from it, you can use the StreamReader class that is equipped with Read() and ReadLine() methods. As done for the StreamWriter class, after using a StreamReader object, make sure you close it.

Here is an example:

Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
			Handles btnOpen.Click
        Dim rdrMembers As StreamReader = New StreamReader("People.txt")
        txtFirstName.Text = rdrMembers.ReadLine()
        txtLastName.Text = rdrMembers.ReadLine()
        txtHomePhone.Text = rdrMembers.ReadLine()
        txtEmailAddress.Text = rdrMembers.ReadLine()
        rdrMembers.Close()
End Sub
 

Practical Learning Practical Learning: Opening a File

  1. Access the module of the first form.
    In the top section of the file, create a class named CEmployee as follows:
     
    Imports System.IO
    
    Public Class CEmployee
        Public EmployeeNumber As String
        Public FullName As String
    End Class
  2. In the Class Name combo box, select txtEmployeeNumber
  3. In the Method Name combo box, select Leave
  4. Implement the new event as follows:
     
    Private Sub txtEmployeeNumber_Leave(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles txtEmployeeNumber.Leave
            ' Create a FileInfo object based on the file that contains the employees
            Dim fleEmployees As FileInfo = New FileInfo("Employees.txt")
            ' Open the file
            Dim stmEmployees As StreamReader = fleEmployees.OpenText()
            ' We will need to create a list of employees from the file
            Dim lstEmployees As ArrayList = New ArrayList
    
            ' Use exception handling just in case
            Try
                ' This String variable will hold a line of text
                Dim strData As String = Nothing
    
                ' "Scan" the file, reading each line
                Do
                    strData = stmEmployees.ReadLine()
    
                    ' We will need to locate each employee
                    Dim empl As CEmployee = New CEmployee
                    ' Get the current line of text as the employee number
                    ' and store its value in the first member of the local class
                    empl.EmployeeNumber = strData
                    ' Store the next line of text as employee name
                    ' in the second member variable of the CEmployee object
                    empl.FullName = stmEmployees.ReadLine()
                    ' Now, store the CEmployee object as an item of the list
                    lstEmployees.Add(empl)
                Loop Until strData = Nothing
            Finally
                stmEmployees.Close()
            End Try
    
            ' After creating a list of employees based on the file,
            ' "scan" the list to locate each employee
            Dim i As Integer
            For i = 0 To lstEmployees.Count - 1
                ' Retrieve each CEmployee object
                Dim empl As CEmployee = lstEmployees(i)
                ' If you find an employee number that corresponds to the value
                ' in the Prepared By text box, retrieve its corresponding
                ' employee name and display it in the next text box
                If empl.EmployeeNumber = txtEmployeeNumber.Text Then
                    txtEmployeeName.Text = empl.FullName
                End If
            Next
    End Sub
  5. Display the form.
    In the Toolbox, click the SaveFileDialog button and click the form
  6. In the Properties window, change its characteristics as follows:
    DefaultExt: txt
    Filter: Loan Preparation (*.txt)|*.txt|All Files(*.*)|
    Title: Save Loan Preparation As
  7. In the Toolbox, click the OpenFileDialog button and click the form
  8. In the Properties window, change its characteristics as follows:
    DefaultExt: txt
    Filter: Loan Preparation (*.txt)|*.txt|All Files(*.*)|
    Title: Open Existing Loan Preparation
  9. Save all
  10. Right-click the form and click View Code
  11. In the top section of the file, import the System.IO namespace:
     
    Imports System.IO
    
    Public Class Form1
  12. In the Class Name combo box, select mnuFileSame
  13. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub mnuFileSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    			Handles mnuFileSave.Click
            If txtEmployeeNumber.Text = "" Or txtEmployeeNumber.Text = "00-000" Then
                MsgBox("You must enter the employee number of the clerk " & _
                  "who prepared the loan")
                txtEmployeeNumber.Text = "00-000"
                txtEmployeeNumber.Focus()
                Exit Sub
            End If
    
            If txtFullName.Text = "" Then
                MsgBox("You must enter the name of the customer whose loan " & _
                  "was prepared")
                txtFullName.Focus()
                Exit Sub
            End If
    
            If txtLoanAmount.Text = "" Or txtLoanAmount.Text = "0.00" Then
                MsgBox("Invalid Loan Amount")
                txtLoanAmount.Focus()
                Exit Sub
            End If
    
            If txtInterestRate.Text = "" Then
                MsgBox("Invalid Interest Rate")
                txtInterestRate.Focus()
                Exit Sub
            End If
    
            If txtPeriods.Text = "" Then
                MsgBox("Invalid number of period")
                txtPeriods.Focus()
                Exit Sub
            End If
    
            CalculateLoan()
    
            If saveFileDialog1.ShowDialog() = DialogResult.OK Then
                Dim fleLoan As FileInfo = New FileInfo(saveFileDialog1.FileName)
                Dim swrLoan As StreamWriter = fleLoan.CreateText()
    
                Try
                    swrLoan.WriteLine(txtEmployeeNumber.Text)
                    swrLoan.WriteLine(txtEmployeeName.Text)
                    swrLoan.WriteLine(txtFullName.Text)
                    swrLoan.WriteLine(txtEmployerName.Text)
                    swrLoan.WriteLine(txtHomePhone.Text)
                    swrLoan.WriteLine(txtWorkPhone.Text)
                    swrLoan.WriteLine(txtLoanAmount.Text)
                    swrLoan.WriteLine(txtInterestRate.Text)
                    swrLoan.WriteLine(txtPeriods.Text)
                    swrLoan.WriteLine(txtPayment.Text)
    
                    txtEmployeeNumber.Text = "00-000"
                    txtEmployeeName.Text = ""
                    txtFullName.Text = ""
                    txtEmployerName.Text = ""
                    txtHomePhone.Text = ""
                    txtWorkPhone.Text = ""
                    txtLoanAmount.Text = "0.00"
                    txtInterestRate.Text = "8.25"
                    txtPeriods.Text = "60"
                    txtPayment.Text = "0.00"
    
                    txtEmployeeNumber.Focus()
                Finally
                    swrLoan.Flush()
                    swrLoan.Close()
                End Try
            End If
     End Sub
  14. In the Class Name combo box, select mnuFileOpen
  15. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub mnuFileOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    			Handles mnuFileOpen.Click
            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                ' Create a FileInfo object based on the file
                Dim fleLoan As FileInfo = New FileInfo(openFileDialog1.FileName)
                ' Open the file
                Dim stmLoan As StreamReader = fleLoan.OpenText()
    
                ' Use exception handling just in case
                Try
                    txtEmployeeNumber.Text = stmLoan.ReadLine()
                    txtEmployeeName.Text = stmLoan.ReadLine()
                    txtFullName.Text = stmLoan.ReadLine()
                    txtEmployerName.Text = stmLoan.ReadLine()
                    txtHomePhone.Text = stmLoan.ReadLine()
                    txtWorkPhone.Text = stmLoan.ReadLine()
                    txtLoanAmount.Text = stmLoan.ReadLine()
                    txtInterestRate.Text = stmLoan.ReadLine()
                    txtPeriods.Text = stmLoan.ReadLine()
                    txtPayment.Text = stmLoan.ReadLine()
                Finally
                    stmLoan.Close()
                End Try
            End If
    End Sub
  16. Execute the application
 

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:

Overrides Public Sub Delete()

Here is an example:

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim fleMembers As FileInfo = New FileInfo("First.txt")
        fleMembers.Delete()
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. The first version has the following syntax:

Overloads Public Function CopyTo(ByVal destFileName As String) As FileInfo

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 Object, ByVal e As System.EventArgs) Handles btnCopy.Click
        Dim fleMembers As FileInfo = New FileInfo("People.txt")
        Dim strMyDocuments As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        fleMembers.CopyTo(strMyDocuments & "\Persons.txt")
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 local computer.

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:

Overloads Public Function CopyTo(ByVal destFileName As String, _
   			      ByVal 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 argument as true; otherwise, pass it as false.

 

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 the file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its syntax is:

Public Sub MoveTo(ByVal 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 Object, ByVal e As System.EventArgs) Handles btnMove.Click
        Dim fleMembers As FileInfo = New FileInfo("Persons.txt")
        Dim strMyDocuments As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        fleMembers.CopyTo(strMyDocuments & "\peeps.txt")
End Sub
 
 

Previous Copyright © 2005-2012 FunctionX Next