Home

Exception Handling in File Processing

  

Finally

We know that, to handle exceptions, we can use the try, catch, and throw keywords. These allow us to perform normal assignments in a try section and then handle an exception, if any, in a catch block. We also know that, when a streaming operation is over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

During file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, the C# language provides a special keyword used free resources. This keyword is finally.

The finally keyword is used to create a section of an exception. Like catch, a finally block cannot exist by itself. It can be created following a try section. The formula used would be:

try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. There are rules associated with this keyword:

  • 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:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>


<html>
<head>

<script runat="server">
private void btnSaveClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Employees.prs");

    FileStream fstPersons = new FileStream(Filename, FileMode.Create);
    BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
    
    try
    {
	wrtPersons.Write(txtFirstName.Text);
    	wrtPersons.Write(txtLastName.Text);

	txtFirstName.Text = "";
    	txtLastName.Text = "";
    }
    finally
    {
    	wrtPersons.Close();
    	fstPersons.Close();
    }
}

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

    try
    {
	txtFirstName.Text = rdrPersons.ReadString();
    	txtLastName.Text = rdrPersons.ReadString();
    }
    finally
    {
    	rdrPersons.Close();
    	fstPersons.Close();
    }
}
</script>

<title>Exercise</title>

</head>
<body>


<form id="frmExercise" runat="server">
  <table>
    <tr>
      <td>First Name:</td>
      <td>
        <asp:TextBox ID="txtFirstName"
                     runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnSave"
                    OnCLick="btnSaveClick"
                    Text="Save" Width="100px"
                    runat="server" />
      </td>
    </tr>
    <tr>
      <td>Last Name:</td>
      <td><asp:TextBox ID="txtLastName"
                       runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnOpen"
                    OnCLick="btnOpenClick"
                    Text="Open" Width="100px"
                    runat="server" />
      </td>
    </tr>
    
  </table>
</form>

</body>
</html>

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).

.NET Framework Exception Handling for File Processing

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, if the file doesn't exist, the operation cannot be carried.  Here is an example:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<html>
<head>

<script runat="server">
private void btnSaveClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Employees.prs");

    FileStream fstPersons = new FileStream(Filename, FileMode.Create);
    BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
    
    try
    {
	wrtPersons.Write(txtFirstName.Text);
    	wrtPersons.Write(txtLastName.Text);

	txtFirstName.Text = "";
    	txtLastName.Text = "";
    }
    finally
    {
    	wrtPersons.Close();
    	fstPersons.Close();
    }
}

private void btnOpenClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Contractors.prs");
    FileStream fstPersons = new FileStream(Filename, FileMode.Open);
    BinaryReader rdrPersons = new BinaryReader(fstPersons);

    try
    {
	txtFirstName.Text = rdrPersons.ReadString();
    	txtLastName.Text = rdrPersons.ReadString();
    }
    finally
    {
    	rdrPersons.Close();
    	fstPersons.Close();
    }
}
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmExercise" runat="server">
  <table>
    <tr>
      <td>First Name:</td>
      <td>
        <asp:TextBox ID="txtFirstName"
                     runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnSave"
                    OnCLick="btnSaveClick"
                    Text="Save" Width="100px"
                    runat="server" />
      </td>
    </tr>
    <tr>
      <td>Last Name:</td>
      <td><asp:TextBox ID="txtLastName"
                       runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnOpen"
                    OnCLick="btnOpenClick"
                    Text="Open" Width="100px"
                    runat="server" />
      </td>
    </tr>
    
  </table>
</form>

</body>
</html>

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

Error

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.

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.

 
 
 

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.

File Initialization

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

 
 
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. Alternatively, if you want, you can provide any valid directory you have access to. In this case, you should provide the complete path.

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 FileStream Create();

This method simply creates an empty file. 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 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.

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:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<html>
<head>

<script runat="server">
private void btnSaveClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Contractor.prs");

    StreamWriter stmWrite = new StreamWriter(Filename);
    
    try
    {
	stmWrite.WriteLine(txtFirstName.Text);
    	stmWrite.WriteLine(txtLastName.Text);

	txtFirstName.Text = "";
    	txtLastName.Text = "";
    }
    finally
    {
    	stmWrite.Close();
    }
}
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmExercise" runat="server">
  <table>
    <tr>
      <td>First Name:</td>
      <td>
        <asp:TextBox ID="txtFirstName"
                     runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnSave"
                    OnCLick="btnSaveClick"
                    Text="Save" Width="100px"
                    runat="server" />
      </td>
    </tr>
    <tr>
      <td>Last Name:</td>
      <td><asp:TextBox ID="txtLastName"
                       runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnOpen" Text="Open" Width="100px" runat="server" />
      </td>
    </tr>
    
  </table>
</form>

</body>
</html>

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 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.

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 StreamReader OpenText();

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

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<html>
<head>

<script runat="server">
private void btnSaveClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Contractors.prs");

    StreamWriter stmWrite = new StreamWriter(Filename);
    
    try
    {
	stmWrite.WriteLine(txtFirstName.Text);
    	stmWrite.WriteLine(txtLastName.Text);

	txtFirstName.Text = "";
    	txtLastName.Text = "";
    }
    finally
    {
    	stmWrite.Close();
    }
}

private void btnOpenClick(object sender, EventArgs e)
{
    string Filename = Server.MapPath("Contractors.prs");
    FileInfo fleContractors = new FileInfo(Filename);
    StreamReader srContractors = fleContractors.OpenText();

    if (fleContractors.Exists == true)
    {
    	try
    	{
	    txtFirstName.Text = srContractors.ReadLine();
    	    txtLastName.Text  = srContractors.ReadLine();
    	}
    	finally
    	{
    	    srContractors.Close();
    	}
    }
}
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmExercise" runat="server">
  <table>
    <tr>
      <td>First Name:</td>
      <td>
        <asp:TextBox ID="txtFirstName"
                     runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnSave"
                    OnCLick="btnSaveClick"
                    Text="Save" Width="100px"
                    runat="server" />
      </td>
    </tr>
    <tr>
      <td>Last Name:</td>
      <td><asp:TextBox ID="txtLastName"
                       runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnOpen"
                    OnCLick="btnOpenClick"
                    Text="Open" Width="100px"
                    runat="server" />
      </td>
    </tr>
    
  </table>
</form>

</body>
</html>
 

 

   
 

Previous Copyright © 2009-2016, FunctionX, Inc. Home