Working with Disk Files






Working with Disk Files

The classes from the System.IO namespace enable you to manipulate the data stored in disk files.

Using the File Class

The File class represents a disk file and contains static methods that enable you to create, open, move, copy, and delete files. It also contains a set of methods that provide access to information about the files.

graphics/alert_icon.gif

The .NET Framework also provides the FileInfo class for working with files. You can do almost everything with the FileInfo class that you can do with the File class. Use the following facts to choose one over another in a given situation:

  • Unlike the File class, the FileInfo class does not contain any static methods; therefore, you need to create an instance of the FileInfo class before using it.

  • The File class performs security checks whenever a static method is called. However, in the case of the FileInfo class, security checks are performed only once when the object is created.

In most cases, you should use the FileInfo class instead of the File class if you are going to reuse an object several times in your program.


Using the FileStream Class

The FileStream class treats a file as a stream of bytes.

Consider the following code segment that uses a FileStream object to create a backup copy of a file:

// Get the physical path of the file
String strFileName = Server.MapPath("XMLFile1.xml");
// Open the file for reading as a stream
FileStream fsIn = File.OpenRead(strFileName);
// Open the file for writing as a stream
FileStream fsOut = File.OpenWrite(strFileName + ".bak");
// Copy all data from in to out, using a 4K buffer
Byte[] buf = new Byte[4096];
int intBytesRead;
while((intBytesRead = fsIn.Read(buf, 0, 4096)) > 0)
     fsOut.Write(buf, 0, intBytesRead);
// Clean up
fsOut.Flush();
fsOut.Close();
fsIn.Close();

This code creates two FileStream objects, one each for the input and output files, by using static methods of the File object (which represents a disk file). The FileStream.Read() method takes three parameters:

  • A buffer to hold the data being read

  • An offset in the buffer where newly read bytes should be placed

  • The maximum number of bytes to read

The Read() method returns the number of bytes that were actually read. Similarly, the Write() method takes three parameters:

  • A buffer to hold the data being written

  • An offset in the buffer where the writing of bytes should begin

  • The number of bytes to write

Using the StreamReader and StreamWriter Classes

The FileStream class is your best option when you don't care (or don't know) about the internal structure of the files with which you're working. But in many cases, you have additional knowledge that lets you use other objects. Text files, for example, are often organized as lines of text separated by end-of-line characters. The StreamReader and StreamWriter classes provide tools for manipulating such files as shown in the following code segment:

// Create a new file to work with
FileStream fsOut = File.Create(Server.MapPath("test.txt"));
// Create a StreamWriter to handle writing
StreamWriter sw = new StreamWriter(fsOut);
// And write some data
sw.WriteLine("Test Data Line 1");
sw.WriteLine("Test Data Line 2");
sw.Flush();
sw.Close();

// Now open the file for reading
FileStream fsIn = File.OpenRead(Server.MapPath("test.txt"));
// Create a StreamReader to handle reading
StreamReader sr = new StreamReader(fsIn);
// And read the data
while (sr.Peek() > -1)
   Response.Write(sr.ReadLine());
sr.Close();
fsIn.Close();
fsOut.Close();

You can think of the StreamWriter and StreamReader classes as forming an additional layer of functionality on top of the FileStream class. The FileStream object handles opening a particular disk file; then it serves as a parameter to the constructor of the StreamWriter or StreamReader object. The code in the previous example first opens a StreamWriter object and calls its WriteLine() method multiple times to write lines of text to the file. It then creates a StreamReader object that uses the same text file. The code uses the Peek() method of the StreamReader object to watch for the end of the file. This method returns the next byte in the file without actually reading it, or it returns -1 if no more data is to be read. As long as there is data to read, the ReadLine() method of the StreamReader object can read it to place in the list box.

In addition to the methods in the previous example, the StreamWriter has a Write() method that writes output without adding a newline character. The StreamReader class implements the Read() and ReadToEnd() methods, which offer additional functionality for reading data. The Read() method reads a specified number of characters, and the ReadToEnd() method reads all the remaining characters to the end of the stream.

Using the BinaryReader and BinaryWriter Classes

For files with known internal structures, the BinaryReader and BinaryWriter classes offer streaming functionality that's oriented toward particular data types. The following code segment demonstrates how to use the BinaryWriter and BinaryReader objects:

// Create a new file to work with
FileStream fsOut = File.Create(Server.MapPath("test.dat"));
// Create a BinaryWriter to handle writing
BinaryWriter bw = new BinaryWriter(fsOut);
// And write some data
Int32 intData1 = 7;
Decimal dblData2 = 3.14159M;
String strData3 = "Pi in the Sky";
bw.Write(intData1);
bw.Write(dblData2);
bw.Write(strData3);
bw.Flush();
bw.Close();
fsOut.Close();

// Now open the file for reading
FileStream fsIn = File.OpenRead(Server.MapPath("test.dat"));
// Create a BinaryReader to handle reading
BinaryReader br = new BinaryReader(fsIn);
// And read the data
lbData.Items.Add("Int32: " + br.ReadInt32());
lbData.Items.Add("Decimal: " + br.ReadDecimal());
lbData.Items.Add("String: " + br.ReadString());
br.Close();
fsIn.Close();

Like the StreamWriter and StreamReader classes, the BinaryWriter and BinaryReader classes provide a layer on top of the basic FileStream class. BinaryWriter and BinaryReader classes are oriented toward writing and reading particular types of data. The BinaryWriter.Write() method has overloads for many data types, so it can handle writing almost anything to a file.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows