Visual C#

Details on File Processing

In previous lessons, to handle exceptions, we were using the try, catch, and throw keywords. These allowed us to perform normal assignments in a try…

12 min read2,622 words13 code samples

Exception Handling in File Processing#

Finally#

We previously used try, catch, and throw to manage exceptions and ensure basic assignments were handled correctly. Since file processing requires the operating system to allocate significant resources, it is essential to return those resources by calling the Close() method when the stream is no longer needed. The C# language provides the finally keyword specifically for this purpose, creating a block that executes after the try and catch sections to ensure resources are freed regardless of whether an error occurred. The structure is as follows:

C#
try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. Like catch, the finally section is created after the try section. Unlike catch, finally never has parentheses and never takes arguments. Unlike catch, the finally section is always executed. Because the finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated previously. In the same way, you can use a finally section to free resources used when reading from a stream. Here are examples:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileProcessing1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            
            FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

            try
            {
                wrtPersons.Write(txtPerson1.Text);
                wrtPersons.Write(txtPerson2.Text);
                wrtPersons.Write(txtPerson3.Text);
                wrtPersons.Write(txtPerson4.Text);

                txtPerson1.Text = "";
                txtPerson2.Text = "";
                txtPerson3.Text = "";
                txtPerson4.Text = "";
            }
            finally
            {
                wrtPersons.Close();
                fstPersons.Close();
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            FileStream fstPersons = new FileStream(Filename, FileMode.Open);
            BinaryReader rdrPersons = new BinaryReader(fstPersons);

            try
            {
                txtPerson1.Text = rdrPersons.ReadString();
                txtPerson2.Text = rdrPersons.ReadString();
                txtPerson3.Text = rdrPersons.ReadString();
                txtPerson4.Text = rdrPersons.ReadString();
            }
            finally
            {
                rdrPersons.Close();
                fstPersons.Close();
            }
        }
    }
}

Of course, since the whole block of code starts with a try section, it is used for exception handling. This means that you can add the necessary and appropriate catch section(s) (but you don't have to). Practical Learning: Finally Releasing Resources

  1. Start Microsoft Visual C# and open the ClarksvilleIceCream2 application from the previous lesson
  2. Right-click the form and click View Code
  3. Change the following two events : private void btnClose_Click(object sender, EventArgs e) { System.Windows.Forms.DialogResult answer = MessageBox.Show( "Do you want to save this order to remember it " + "the next time you come to " + "get your ice scream?", "Ice Cream Vending Machine", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (answer == System.Windows.Forms.DialogResult.Yes) { string Filename = Microsoft.VisualBasic.Interaction.InputBox( "Please type your initials and press Enter", "Ice Cream Vending Machine", "AA", 100, 100); if (Filename != "") { Filename = Filename + ".icr"; FileStream stmIceCream = new FileStream(Filename, FileMode.Create); BinaryWriter bnwIceCream = new BinaryWriter(stmIceCream); try { bnwIceCream.Write(dtpOrderDate.Value.ToShortDateString()); bnwIceCream.Write(dtpOrderTime.Value.ToShortTimeString()); bnwIceCream.Write(cboFlavors.Text); bnwIceCream.Write(cboContainers.Text); bnwIceCream.Write(cboIngredients.Text); bnwIceCream.Write(txtScoops.Text); bnwIceCream.Write(txtOrderTotal.Text); } finally { bnwIceCream.Close(); stmIceCream.Close(); } MessageBox.Show("The order has been saved"); } else MessageBox.Show("The ice cream order will not be saved"); } MessageBox.Show("Good Bye: It was a delight serving you"); Close(); } private void Form1_Load(object sender, EventArgs e) { string Filename = Microsoft.VisualBasic.Interaction.InputBox( "If you had previously ordered an ice cream here " + "and you want to order the same, please type your " + "initials and press Enter (otherwise, press Esc)", "Ice Cream Vending Machine", "", 100, 100); if(Filename != "") { Filename = Filename + ".icr"; string OrderDate; string OrderTime; string SelectedFlavor; string SelectedContainer; string SelectedIngredient; string Scoops; string OrderTotal; FileStream stmIceCream = new FileStream(Filename, FileMode.Open); BinaryReader bnrIceCream = new BinaryReader(stmIceCream); // Find out if this order was previously saved in the machine if (File.Exists(Filename)) { // If so, open it try { OrderDate = bnrIceCream.ReadString(); OrderTime = bnrIceCream.ReadString(); SelectedFlavor = bnrIceCream.ReadString(); SelectedContainer = bnrIceCream.ReadString(); SelectedIngredient = bnrIceCream.ReadString(); Scoops = bnrIceCream.ReadString(); OrderTotal = bnrIceCream.ReadString(); // And display it to the user dtpOrderDate.Value = DateTime.Parse(OrderDate); dtpOrderTime.Value = DateTime.Parse(OrderTime); cboFlavors.Text = SelectedFlavor; cboContainers.Text = SelectedContainer; cboIngredients.Text = SelectedIngredient; txtScoops.Text = Scoops.ToString(); txtOrderTotal.Text = OrderTotal; } finally { bnrIceCream.Close(); stmIceCream.Close(); } } else MessageBox.Show("It looks like you have not previously " + "ordered an ice cream here"); } }
  4. Execute the application and test it
  5. Close the form

.NET Framework Exception Handling for File Processing#

In the previous lesson as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of. One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases you can provide this name to the application or document. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler is asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. Here is an example:

C#
private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";
    FileStream fstPersons = null;
    BinaryReader rdrPersons = null;

    fstPersons = new FileStream(Filename, FileMode.Open);
    rdrPersons = new BinaryReader(fstPersons);

    try
    {
        txtPerson1.Text = rdrPersons.ReadString();
        txtPerson2.Text = rdrPersons.ReadString();
        txtPerson3.Text = rdrPersons.ReadString();
        txtPerson4.Text = rdrPersons.ReadString();
    }
    finally
    {
        rdrPersons.Close();
        fstPersons.Close();
    }
}

Here is an example of an error that this would produce:

There are many other exceptions that can thrown as a result of something going bad during file processing: FileNotFoundException: This exception is thrown when a file has not been found. Here is an example of handling it:

C#
private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";

    try
    {
        FileStream fstPersons = new FileStream(Filename, FileMode.Open);
        BinaryReader rdrPersons = new BinaryReader(fstPersons);

        try
        {
            txtPerson1.Text = rdrPersons.ReadString();
            txtPerson2.Text = rdrPersons.ReadString();
            txtPerson3.Text = rdrPersons.ReadString();
            txtPerson4.Text = rdrPersons.ReadString();
        }
        finally
        {
            rdrPersons.Close();
            fstPersons.Close();
        }
    }
    catch(FileNotFoundException ex)
    {
        Console.Write("Error: " + ex.Message);
        MessageBox.Show(" May be the file doesn't exist or you typed it wrong!");
    }
}

Here is an example of what this would produce:

IOException: As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can throw the IOException exception. Practical Learning: Handling File Processing Exceptions

  1. In the Types combo box, select IceCream1.Form1 and, in the Members combo box, select Form1_Load
  2. To handle a FileNotFoundException exception, change the event as follows: private void Form1_Load(object sender, EventArgs e) { string Filename = Microsoft.VisualBasic.Interaction.InputBox( "If you had previously ordered an ice cream here " + "and you want to order the same, please type your " + "initials and press Enter (otherwise, press Esc)", "Ice Cream Vending Machine", "", 100, 100); if (Filename != "") { Filename = Filename + ".icr"; string OrderDate; string OrderTime; string SelectedFlavor; string SelectedContainer; string SelectedIngredient; string Scoops; string OrderTotal; try { FileStream stmIceCream = new FileStream(Filename, FileMode.Open); BinaryReader bnrIceCream = new BinaryReader(stmIceCream); // Find out if this order was previously saved in the machine if(File.Exists(Filename)) { // If so, open it try { OrderDate = bnrIceCream.ReadString(); OrderTime = bnrIceCream.ReadString(); SelectedFlavor = bnrIceCream.ReadString(); SelectedContainer = bnrIceCream.ReadString(); SelectedIngredient = bnrIceCream.ReadString(); Scoops = bnrIceCream.ReadString(); OrderTotal = bnrIceCream.ReadString(); // And display it to the user dtpOrderDate.Value = DateTime.Parse(OrderDate); dtpOrderTime.Value = DateTime.Parse(OrderTime); cboFlavors.Text = SelectedFlavor; cboContainers.Text = SelectedContainer; cboIngredients.Text = SelectedIngredient; txtScoops.Text = Scoops.ToString(); txtOrderTotal.Text = OrderTotal; } finally { bnrIceCream.Close(); stmIceCream.Close(); } } else MessageBox.Show("It looks like you have not previously " + "ordered an ice cream here"); } catch (FileNotFoundException) { MessageBox.Show("There is no previous order with those initials"); } } }
  3. Exercise the application and test it
  4. Close the form

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

  1. To start a new application, on the main menu, click File -> New -> Project
  2. In the Templates list, click Windows Application
  3. Set the name to WattsALoan1
  4. In the Properties window, change the form's Text to Watts A Loan
  5. To be able to use the Visual Basic library, in the Solution Explorer, right-click WattsALoan1 and click Add Reference...
  6. In the .NET property page, click Microsoft.VisualBasic
  7. Click OK
  8. Design the form as follows: 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 Label Interest Rate: TextBox txtInterestRate Label % Label Periods TextBox txtPeriods Button btnCalculate Calculate Label Monthly Payment: TextBox txtMonthlyPayment Button btnClose Close
  9. Double-click the Calculate button and implement its event as follows: private void btnCalculate_Click(object sender, EventArgs e) { double LoanAmount = 0.00D, InterestRate = 0.00D, Periods = 0.00D, MonthlyPayment = 0.00D; try { LoanAmount = double.Parse(txtLoanAmount.Text); } catch (FormatException) { MessageBox.Show("Invalid Loan Amount"); } try { InterestRate = double.Parse(txtInterestRate.Text); } catch (FormatException) { MessageBox.Show("Invalid Interest Rate"); } try { Periods = double.Parse(txtPeriods.Text); } catch (FormatException) { MessageBox.Show("Invalid Periods Value"); } try { MonthlyPayment = Microsoft.VisualBasic.Financial.Pmt(InterestRate/12/100, Periods, -LoanAmount, 0, Microsoft.VisualBasic.DueDate.BegOfPeriod); txtMonthlyPayment.Text = MonthlyPayment.ToString("F"); } catch (FormatException) { MessageBox.Show("Invalid Periods Value"); } }
  10. Return to the form and double-click the Close button to implement its event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  11. Return to the form

File Initialization#

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

C#
public FileInfo(String fileName);

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. Here is an example:

C#
public partial class Exercise : Form
{
    private void btnSave_Click(object sender, EventArgs e)
    {
        FileInfo flePeople = new FileInfo("People.txt");
    }
}

You also have the option to specify any valid directory path that you have permission to access, provided you use the full path. Practical Exercise: Setting Up a File.

  1. Double-click an unoccupied area on the body form
  2. Scroll up completely and, under the other using lines, type using System.IO;
  3. Scroll down complement and change the Load event of the form as follows: private void Form1_Load(object sender, EventArgs e) { string strFilename = "Employees.wal"; FileInfo fiEmployees = new FileInfo(strFilename); }
  4. 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:

C#
public FileStream Create();

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

C#
private void btnSave_Click(object sender, EventArgs e)
{
    FileInfo flePeople = new FileInfo("People.txt");
    flePeople.Create();
}

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:

C#
public StreamWriter CreateText();

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 the right 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 doesn't exist or it doesn't exist in the path. Practical Learning: Creating a Text File

  1. Change the Load event of the form as follows: private void Form1_Load(object sender, EventArgs e) { string strFilename = "Employees.wal"; FileInfo fiEmployees = new FileInfo(strFilename); // If the employees file was not created already, // then create it if (!fiEmployees.Exists) { StreamWriter stwEmployees = fiEmployees.CreateText(); } }
  2. Save the file

Writing to a File#

As mentioned earlier, the FileInfo.Create() method returns a 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. This method returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with the Write() and the WriteLine() methods used to write values to a file. The Write() method writes text on a line and keeps the caret on the same line. The WriteLine() method writes a line of text and moves the caret to the next line. After writing to a file, you should close the StreamWriter object to free the resources it was using during its operation(s). Here is an example:

C#
private void btnSave_Click(object sender, EventArgs e)
{
    FileInfo flePeople = new FileInfo("People.txt");
    StreamWriter stwPeople = flePeople.CreateText();

    try
    {
        stwPeople.WriteLine(txtPerson1.Text);
        stwPeople.WriteLine(txtPerson2.Text);
        stwPeople.WriteLine(txtPerson3.Text);
        stwPeople.WriteLine(txtPerson4.Text);
    }
    finally
    {
        stwPeople.Close();

        txtPerson1.Text = "";
        txtPerson2.Text = "";
        txtPerson3.Text = "";
        txtPerson4.Text = "";
    }
}

Practical Learning: Writing to a Text File

  1. Change the Load event of the form as follows: private void Form1_Load(object sender, EventArgs e) { string strFilename = "Employees.wal"; FileInfo fiEmployees = new FileInfo(strFilename); // If the employees file was not created already, // then create it if (!fiEmployees.Exists) { StreamWriter stwEmployees = fiEmployees.CreateText(); // And create a John Doe employee try { stwEmployees.WriteLine("00-000"); stwEmployees.WriteLine("John Doe"); } finally { stwEmployees.Close(); } } }
  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:

C#
public StreamWriter AppendText();

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 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, under the using using lines, type using System.IO;
  6. Return to the New Employee form and double-click the Create button
  7. Implement its event as follows: private void btnCreate_Click(object sender, EventArgs e) { string strFilename = "Employees.wal"; FileInfo fiEmployees = new FileInfo(strFilename); StreamWriter stwEmployees = null; // Normally, we should have the file already but just in case... if( !fiEmployees.Exists ) stwEmployees = fiEmployees.CreateText(); else // If the file exists already, then we will only add to it stwEmployees= fiEmployees.AppendText(); try { stwEmployees.WriteLine(txtEmployeeNumber.Text); stwEmployees.WriteLine(txtEmployeeName.Text); } finally { stwEmployees.Close(); } txtEmployeeNumber.Text = ""; txtEmployeeName.Text = ""; txtEmployeeNumber.Focus(); }
  8. Return to the New Employee form and double-click the Close button
  9. Implement its event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
  10. Access the Form1 form
  11. Double-click the top New button and implement the event as follows: private void btnNewEmployee_Click(object sender, EventArgs e) { NewEmployee frmNewEmployee = new NewEmployee(); frmNewEmployee.ShowDialog(); }
  12. Return to the form
  13. In the combo box on top of the Properties window, select txtEmployeeNumber
  14. On the Properties window, click the Events button and double-click Leave
  15. Implement the event as follows: private void txtEmployeeNumber_Leave(object sender, EventArgs e) { string strFilename = "Employees.wal"; FileInfo fiEmployees = new FileInfo(strFilename); if (fiEmployees.Exists) { if (txtEmployeeNumber.Text == "") { txtEmployeeName.Text = ""; return; } else { StreamReader strEmployees = fiEmployees.OpenText(); string strEmployeeNumber, strEmployeeName; bool found = false; try { using (strEmployees = new StreamReader(strFilename)) { while (strEmployees.Peek() >= 0) { strEmployeeNumber = strEmployees.ReadLine(); if (strEmployeeNumber == txtEmployeeNumber.Text) { strEmployeeName = strEmployees.ReadLine(); txtEmployeeName.Text = strEmployeeName; found = true; } } } // When the application has finished checking the file // if there was no employee with that number, let the user know if (found == false) { MessageBox.Show("No employee with that number was found"); txtEmployeeName.Text = ""; txtEmployeeNumber.Focus(); } } finally { strEmployees.Close(); } } } }
  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
  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:

C#
public StreamREader OpenText();

Using this method will give you a StreamReader object, which you can then use to read through the lines of a text file. Consider this example:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FileProcessing2
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            FileInfo flePeople = new FileInfo("People.txt");
            StreamWriter stwPeople = flePeople.CreateText();

            try
            {
                stwPeople.WriteLine(txtPerson1.Text);
                stwPeople.WriteLine(txtPerson2.Text);
                stwPeople.WriteLine(txtPerson3.Text);
                stwPeople.WriteLine(txtPerson4.Text);
            }
            finally
            {
                stwPeople.Close();

                txtPerson1.Text = "";
                txtPerson2.Text = "";
                txtPerson3.Text = "";
                txtPerson4.Text = "";
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string Filename = "People.txt";
            FileInfo flePeople = new FileInfo(Filename);
            StreamReader strPeople = flePeople.OpenText();

            if (flePeople.Exists == true)
            {
                try
                {
                    txtPerson1.Text = strPeople.ReadLine();
                    txtPerson2.Text = strPeople.ReadLine();
                    txtPerson3.Text = strPeople.ReadLine();
                    txtPerson4.Text = strPeople.ReadLine();
                }
                finally
                {
                    strPeople.Close();
                }
            }
            else
                MessageBox.Show("There is no file named People.txt " +
                                "in the indicated location");
        }
    }
}

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

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 C# Key Next