Chapter 4c

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

 Introduction

 The FileStream Class


 Random and sequential file access
 Handling text file
 The File and Directory Classes

2
 Up until we are only creating programs that could accept data
at runtime, when a program is terminated, the data also
disappear.
 It is possible to save data accepted by a C# program into a
storage device, such as a hard disk or diskette, or even CDRW.
 A file is a collection of data stored on a disk or on some other
relatively permanent storage medium.
 A file's existence does not depend on a running program.
 In this lecture, we will learn how to create files by writing them
into a storage device and then retrieve the data by reading the
contents of the files using C#.net programs.
3
 In C# .NET, file handling is largely based on the System.IO
namespace, which is a class library that supports string,
character, and file manipulation.
 These classes include properties, methods, and events for
creating, copying, moving, and deleting files.
 The most commonly used classes are FileStream, BinaryReader,
BinaryWriter, StreamReader, and StreamWriter, and we'll take
a look at these classes .
 Tip
 File handling is one of the most error-prone of all possible
programming operations. It's best to always enclose your code in
try/catch blocks here to handle problems.
4
 The FileStream class gives you access to files.You start working with
a file on disk by opening it or creating it; you can use the members
of the FileAccess, FileMode, and FileShare enumerations with the
constructors of the FileStream class to determine how the file is
created, opened, and shared.
 After you've opened or created a file, you can pass its FileStream
object to the BinaryReader, BinaryWriter, StreamReader, and
StreamWriter classes to actually work with the data in the file.

5
 You also can use the FileStream Seek method to move to various
locations in a file—this is called moving the read/write position or
the read/write pointer.
 This allows you to break a file up into records. For example, if you're
keeping track of 2,000 employees, you can create 2,000 records in a
file, each with data on the corresponding employee.
 This record-based process, where you can move around in a file and
select the data you want, is called random access.
 The other form of file access, where you just read or write data to a
file one item after the other—and so you must read through the first
2001 data items if you want to read the 2002th—is called sequential
access.
 The only difference between these types of access from our point of
6
view is that for random access, you use the Seek method.
 To work with text data in files—that is, storing and reading text to and
from files—you can use the StreamReader and StreamWriter classes.
 The StreamReader class is actually derived from an abstract class
called TextReader, which reads characters from a stream, and the
StreamWriter class is derived from an abstract class called TextWriter,
which writes characters to a stream.
 Lets see an example that uses these classes named StreamWriter and
Reader; the example will write text to a file, file.txt, and then read
that text back, displaying it in a text box.
 In order to do that
 Start by importing the System.IO namespace, and by creating file.txt and
connecting a FileStream object to it.
 Next, you can create a StreamWriter object and use various methods to
7 move around in and write text to the file.
 The Seek method is used to move to the beginning of the file (that's
not necessary in newly created or opened files because when you open
a file, you start at the beginning of the file— it is just to show you how
Seek works).
 Then a line of text is written with the WriteLine method, and then a
text of file is written with the Write method (the WriteLine method is
the same as Write, except it adds a carriage-return/linefeed pair at the
end of the text it writes).
 File handling is buffered in C#, nothing is written to disk until the
buffer is flushed.
 This happens automatically when the buffer is full or when you close a
file, but you also can use the flush method to explicitly flush data to the
disk.
 Close method is used to close the file on disk, which finishes our work
with the file and makes it available to other programs.
8
 Create a new project add a button double click on it and add the following
code.
 FileStream fs=new FileStream("D:\\file.txt",
FileMode.Create, FileAccess.Write);
 StreamWriter w = new StreamWriter(fs);
 w.BaseStream.Seek(0, SeekOrigin.End);
 w.WriteLine("Here is the file's text.");
 w.WriteLine("Here is more file text.");
 w.WriteLine("And that's about it.");
 w.Flush();
w.Close ();

 using System.IO should be added before the class definition.


 Now that the file, file.txt, has been created and had some text placed in it.
9
Check it out !
 The file created so far can be opened with another FileStream
object, then connected to a StreamReader object to it, and use the
StreamReader object's methods like ReadLine to read data from the
file line by line.
 How can you determine if there's still more data to read in the file?
 You can use the StreamReader object's Peek method, which tells you
how much more data there is remaining in the file.
 If there's no more data, Peek returns a value of -1. If there is more
data, It'll keep reading it in and displaying it in a multi-line text box,
like as follows:

10
 Add the following code at the end of the code you added after double
clicking a button.
 FileStream fs = new FileStream("D:\\file.txt", FileMode.Open,
FileAccess.Read);
 StreamReader r = new StreamReader(fs);
 r.BaseStream.Seek(0, SeekOrigin.Begin);
 while (r.Peek() > -1)
 {textBox1.Text += r.ReadLine()+"\n";}
 r.Close();
 Note in particular the Seek statement.You pass this method the number of
bytes to move from the current position (this value can be positive or
negative), and the origin that you want to move from; and you define the
origin with a value from the SeekOrigin enumeration: SeekOrigin.Begin for
the beginning of the file, SeekOrigin.Current for the current location in the
11
file, or SeekOrigin.End for the end of the file.
 Two other classes you should know about are File and Directory.
 The File class lets you handle files without opening them, allowing
you to move and copy them, and so on.
 The Directory class lets you work with directories, renaming and
creating them.
 In fact, the methods that let you do this are class methods, so you
don't have to create any File and Directory objects first.
 The example on next page first lets you create a directory and then
copy a file to it, using File and Directory methods.
 First, the user enters the path of a new directory into the text box in
this example, and clicks the "Create directory" button, which uses
the Directory class's CreateDirectory method to create the directory:
12
 Create a new project and design the following UI
 Double click create Directory button and add the following
code
 try
 {
 Directory.CreateDirectory(textBox1.Text);
 MessageBox.Show("Directory created.");
 }
 catch
 { MessageBox.Show("Could not create directory."); }
 Next, lets us use the File class's methods
 The first one uses Copy method
13
 try
 {File.Copy(txtSource.Text, txtDestination.Text);
 MessageBox.Show("The file has been successfully copied.");}
 catch
 {MessageBox.Show("Could not copy file.");}

 MessageBox.Show("File copied.");
Check whether a file exists:
 private bool Fileexists()
 {
 if (!(File.Exists(txtSource.Text)))
 {
 MessageBox.Show("The source file does not exist!");
 return false;
 }
 else
 { return true; }

14
}
 File.Move(txtSource.Text, txtDestination.Text);-Moving and renaming file

Delete file
 if (!Fileexists())
 return;
 else{
 if (MessageBox.Show("Are you sure you want to delete the source
file?","MyApp",
 MessageBoxButtons.YesNo , MessageBoxIcon.Question) ==
System.Windows.Forms.DialogResult.Yes)
 {System.IO.File.Delete(txtSource.Text);
 MessageBox.Show("The file has been successfully deleted.");}}

You might also like