ASP.NET

Introduction to File Processing

A file is a series of bytes of data that are arranged in a particular manner to produce a usable document. For easy storage, location, and management, the…

7 min read1,541 words13 code samples

ASP.NET File Processing: Introduction

Introduction to File Processing#

Overview of File Processing and Definitions#

Introduction to Files#

A file is a sequence of bytes arranged in a specific order so that it can form a usable document. For simple storage, retrieval, and organization, those bytes are kept on media such as a hard disc, a floppy disc, a compact disc, or another supported storage medium. When a set of bytes belongs to one logical entity and contains values saved on a medium, that collection is called a file.

File Streaming Prerequisites#

To enable file processing, the .NET Framework offers the System.IO namespace, which includes many classes for handling nearly any file operation you may need. So, if you want to do file processing, add System.IO to your project. Stream is the base class behind file processing. With a stream, you can send data to it or read data back from it. Because Stream is abstract, you cannot create a variable of that type directly in your application. Instead, it serves as the parent for the classes that actually implement the needed behavior. In practice, you usually combine several classes to carry out a typical operation. For example, some classes create the stream object while others write data into that stream.

The Name of a File#

To perform file processing, you must provide a name for the file. The name is of type string. You can provide the name and its extension. To assist you with specifying the name and location of the file, the Server class of IIS is equipped with a static method named MapPath. Its syntax is:

C#
public void MapPath(string Path);

This method takes one required argument: the name of the file. The name follows the rules established by the Internet Information Server. Based on this, the name must not contain the following: a comma, ', ", *, ?, <, >, :, ;, [, //, or \\. The name can represent the relative or virtual path to the file. Here is an example:

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

<html>
<head>

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

<title>Exercise</title>

</head>
<body>

</body>
</html>

If you specify just the name of the file, the directory of the function, method, of event that called it would be considered. Normally, that would be the same directory of the current project. As an alternative, you can precede the name of the file with either a backslash "\" or a forward slash "/". In this case, the string would be considered as representing a complete path.

The .NET Support for Files#

Introduction#

The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

File Existence#

One of the valuable operations that the File class can perform is to check the existence of the file you want to use. To assist you with this, the File class provides the Exists() method. Its syntax is:

C#
public static bool Exists(string path);

File Creation#

Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows:

C#
public static FileStream Create(string path);
public static FileStream Create(string path, int buffersize);

In both cases, the File.Create() method returns a Stream value, in this case a FileStream value. As the File.Create() method indicates, it takes the name or path of the file as argument. If you know or want to specify the size, in bytes, of the file, you can use the second version. To provide the same operation of creating a file, you can use the Open() method of the File class. It is overloaded in three versions as follows:

C#
public static FileStream Open(string path, FileMode mode);
public static FileStream Open(string path, 
		               FileMode mode, 
		               FileAccess access);
public static FileStream Open(string  path,
                          	               FileMode mode,
       		               FileAccess access,
   		               FileShare share);

Access to a File#

In order to perform an operation on a file, you must specify how to proceed. One of the options you have is to indicate the type of access that will be granted on the file. This access is specified using the FileAccess enumerator. The members of the FileAccess enumerator are:

  • FileAccess.Write : New data can be written to the file
  • FileAccess.Read : Existing data can be read from the file
  • FileAccess.ReadWrite : Existing data can be read from the file and new data be written to the file

File Sharing#

When an operation must be performed on a file, you may have to specify how a file can be shared. This is done through the FileShare enumerator. The values of the FileShare enumerator are:

  • FileShare.Inheritable : Allows other file handles to inherit from this file
  • FileShare.None : The file cannot be shared
  • FileShare.Read : The file can be opened and read from
  • FileShare.Write : The file can be opened and written to
  • FileShare.ReadWrite : The file can be opened to write to it or read from it

The Mode of a File#

Besides the access to the file, another option you will most likely specify to the operating system is referred to as the mode of a file. It is specified through the FileMode enumerator. The members of the FileMode Enumerator are:

  • FileMode.Append : If the file already exists, the new data will be added to its end. If the file doesn't exist, it will be created and the new data will be added to it
  • FileMode.Create : If the file already exists, it will be deleted and a new file with the same name will be created. If the file doesn't exist, then it will be created
  • FileMode.CreateNew : If the new already exists, the compiler will throw an error. If the file doesn't exist, it will be created
  • FileMode.Open : If the file exists, it will be opened. If the file doesn't exist, an error would be thrown
  • FileMode.OpenOrCreate : If the file already exists, it will be opened. If the file doesn't exist, it will be created
  • FileMode.Truncate : If the file already exists, its contents will be deleted completely but the file will be kept, allowing you to write new data to it. If the file doesn't exist, an error would be thrown

Fundamentals of File Streaming#

Introduction#

File streaming consists of performing one of the routine operations on a file, such as creating or opening it. This basic operation can be performed using a class called FileStream. You can use a FileStream object to get a stream ready for processing. As one of the most complete classes of file processing of the .NET Framework, FileStream is equipped with all necessary properties and methods. To use it, you must first declare a variable of it. The class is equipped with nine constructors. One of the constructors (the second) of the FileStream class has the following syntax:

C#
public FileStream(string path, FileMode mode);

This constructor takes as its first argument the name of the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example:

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


<html>
<head>

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

    FileStream fstPersons = new FileStream(Filename, FileMode.Create);
}
</script>

<title>Exercise</title>

</head>
<body>

</body>
</html>

Stream Writing#

A streaming operation is typically used to create a stream. Once the stream is ready, you can write data to it. The writing operation is performed through various classes. One of these classes is BinaryWriter. The BinaryWriter class can be used to write values of primitive data types (char, int, float, double, etc). To use a BinaryWriter value, you can first declare its variable. To do this, you would use one of the class' three constructors. The first constructor is the default, meaning it doesn't take an argument. The second constructor has the following syntax:

C#
public BinaryWriter(Stream output);

This constructor takes as argument a Stream value, which could be a FileStream variable. Here is an example:

C#
<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);
}
</script>

Most classes that are used to add values to a stream are equipped with a method called Write. This is also the case for the BinaryWriter class. This method takes as argument the value that must be written to the stream. The method is overloaded so that there is a version for each primitive data type. Here is an example:

C#
<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);
    
    wrtPersons.Write(txtFirstName.Text);
    wrtPersons.Write(txtLastName.Text);
}
</script>

Stream Closing#

When you use a stream, it requests resources from the operating system and uses them while the stream is available. When you are not using the stream anymore, you should free the resources and make them available again to the operating system so that other services can use them. This is done by closing the stream. To close a stream, you can can call the Close() method of the class(es) you were using. Here are examples:

C#
<%@ 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);
    
    wrtPersons.Write(txtFirstName.Text);
    wrtPersons.Write(txtLastName.Text);

    txtFirstName.Text = "";
    txtLastName.Text = "";

    wrtPersons.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>&nbsp;</td>
    </tr>
    <tr>
      <td>Last Name:</td>
      <td><asp:TextBox ID="txtLastName"
                       runat="server"></asp:TextBox>
      </td>
      <td>
        <asp:Button id="btnSave" OnCLick="btnSaveClick"
                    Text="Save" Width="100px" runat="server" />
      </td>
    </tr>
    
  </table>
</form>

</body>
</html>

Stream Reading#

As opposed to writing to a stream, you may want to read existing data from it. Before doing this, you can first specify your intent to the streaming class using the FileMode enumerator. Once the stream is ready, you can get prepared to read data from it. To support this, you can use the BinaryReader class. This class provides two constructors. One of the constructors (the first) has the following syntax:

C#
public BinaryReader(Stream input);

This constructor takes as argument a Stream value, which could be a FileStream object. After declaring a FileStream variable using this constructor, you can read data from it. To support this, the class provides an appropriate method for each primitive data type. After using the stream, you should close it to reclaim the resources it was using. This is done by calling the Close() method. Here is an example of using the mentioned methods:

C#
<%@ 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);
    
    wrtPersons.Write(txtFirstName.Text);
    wrtPersons.Write(txtLastName.Text);

    txtFirstName.Text = "";
    txtLastName.Text = "";

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

    txtFirstName.Text = rdrPersons.ReadString();
    txtLastName.Text = rdrPersons.ReadString();

    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>

Home Copyright © 2009 C# Key Next