Files and Streams
Files
A file is an ordered and
named collection of a particular sequence of bytes having persistent storage.
. Just as there are
several backing stores other than disks, there are several kinds of streams other
than file streams. For example, there
are network, memory, and tape streams.
The System.IO namespace
contains types that allow synchronous and asynchronous reading and writing on
data streams and files.
What is the use Files?
There are many applications
in which we need to backup the database or to send the data to another user
through email. In all those applications
you can use any database but the same operations can also be performed
using a file system.
Another good reason
could be some companies cannot afford to buy expensive databases and
their only choice to collect data is
in the form of files. Also there could be some operations for which
files will be the best option.
Types of Files
The most common type file
system includes:
- text files
- binary files
- xml files
Text Files
Text files are the most
common type of files.
You can make text files in
every editor, notepad is preferably used to make text files.
The extension of the text
file is .txt
Writing text files:
The following example stores data entered in the textbox to the file.
using System.IO;
private void
Button1_Click(object sender, System.EventArgs e)
{
FileStream
fs = File.Create(Server.MapPath("test.txt"));
StreamWriter sw = new
StreamWriter(fs);
sw.Write(TextBox1.Text);
sw.Close();
fs.Close();
}
Explanation
·
Import the System.IO namespace.
·
Make the object of FileStream class.
·
Next we make the object of the StreamWriter class.
·
File.Create method makes a new file. The Server.MapPath means that
file will be created in the virtual folder of IIS which will be located
at C:\inetpub\wwwroot\YourProjectFolder\
·
Next we write the Text from the TextBox to the file using the
StreamWriter Write method.
·
Finally and the most important step is to close the FileStream object
explicitly using the Close method.
Reading Text Files
Reading is also as
simple as writing the text files.
Coding:
private void
Button1_Click(object sender, System.EventArgs e)
{
FileStream fs =
File.OpenRead(Server.MapPath("test.txt"));
StreamReader sr = new StreamReader(fs);
while(sr.Peek() > -1)
{
Response.Write(sr.ReadLine());
}
sr.Close();
fs.Close();
}
Explanation
·
First we made the FileStream object and tells it to open the file
"test.txt".
·
We make the StreamReader object and tell it what FileStream to read.
·
The while loop checks the end of the file when the end of the file is
reached sr.Peek() returns '-1' and the loop breaks.
·
Finally we close the StreamReader and FileStream objects.
Writing binary
files:
For files with known
internal structures, the BinaryReader and BinaryWriter classes offer streaming
functionality that's oriented towards particular data types.
The good thing about
writing binary files are you cannot read the files by just opening them in the
notepad also binary files can be of very large size.
Lets look at the
code to create Binary files.
private void
Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.Create(Server.MapPath("test.dat"));
BinaryWriter bw = new BinaryWriter(fs);
int x = 10;
decimal d = 3.234M;
string str = "Hello World";
bw.Write(x);
bw.Write(d);
bw.Write(str);
bw.Close();
fs.Close();
}
{
FileStream fs = File.Create(Server.MapPath("test.dat"));
BinaryWriter bw = new BinaryWriter(fs);
int x = 10;
decimal d = 3.234M;
string str = "Hello World";
bw.Write(x);
bw.Write(d);
bw.Write(str);
bw.Close();
fs.Close();
}
Explanation
·
First we made the FileStream object but in this case we are writing the
.dat file which means the data file.
·
We created an object of the BinaryWriter class.
·
Later we declared three variables of type int, decimal and string.
·
Finally we wrote the three variables in the binary file.
Reading Binary Files
To read from Binary File we need BinaryReader class
private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs =
File.OpenRead(Server.MapPath("test.dat"));
BinaryReader br = new BinaryReader(fs);
Response.Write(br.ReadInt32());
Response.Write(br.ReadDecimal());
Response.Write(br.ReadString());
br.Close();
BinaryReader br = new BinaryReader(fs);
Response.Write(br.ReadInt32());
Response.Write(br.ReadDecimal());
Response.Write(br.ReadString());
br.Close();
fs.Close();
}
The code for reading
binary files is also very simple. Here we are extracting the data types that we
wrote in the binary file. We use ReadInt32() method to read the integer out
from the binary file. We use ReadDecimal() to read the decimal values from the
binary file and so on.
XML Files
Writing and Reading
Xml files are most important because sometimes they can also be used as a
database.
XmlTextWriter class
Write XML as raw
data implementation of the XmlWriter class that provides the API which writes
XML to file, stream, or a TextWriter.
This class provides
numerous validation and checking rules to ensure that the XML being written is
well formed.
When certain
violations occur, exceptions are thrown and these exceptions should be handled.
has different
constructors, each of which specifies a different type of the location to which
to write the XML data.
Sample:This sample
uses the constructor that writes XML to a file. In particular, the following
sample code constructs an XmlTextWriter with a string representing the file
location for the newbooks.xml file.
Code:
XmlTextWriter myXmlTextWriter = new XmlTextWriter ("newbook.xml", null);
myXmlTextWriter.WriteComment("This file represents another fragment of a book store inventory database");
myXmlTextWriter.WriteStartElement("books");
myXmlTextWriter.WriteStartElement("book", null);
myXmlTextWriter.WriteAttributeString("publicationdate","2012");
myXmlTextWriter.WriteAttributeString("ISBN","0-1212-1122-9");
myXmlTextWriter.WriteElementString("title", null, "FileStreams in ASP.NET");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name", "Blessy");
myXmlTextWriter.WriteElementString("last-name", "Alexander");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "200");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();
Reading XML File
XmlReader class is
the API that provides XML parsing, the XmlTextReader is the implementation designed
to handle byte streams.
This sample loads XML from the books.xml file, as shown in the following code.
code
XmlTextReader reader
= new XmlTextReader ("books.xml");
while
(reader.Read())
{
// Do some work here on the data
...
}
{
// Do some work here on the data
...
}
while
(reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read attributes
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
break;
case XmlNodeType.DocumentType: // The node is a DocumentType
Console.WriteLine(NodeType + "<" + reader.Name + ">" + reader.Value);
break;
...
}
}
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read attributes
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
break;
case XmlNodeType.DocumentType: // The node is a DocumentType
Console.WriteLine(NodeType + "<" + reader.Name + ">" + reader.Value);
break;
...
}
}
Streams
The abstract base
class Stream supports reading and writing
bytes. Its default
implementations define synchronous reads and writes in terms of their
corresponding asynchronous methods, and vice versa.
All classes that
represent streams inherit from the Stream class.
Streams involve
these fundamental operations:
Streams can be read
from. Reading is the transfer of data from a stream into a data structure, such
as an array of bytes.
Streams can be
written to. Writing is the transfer of data from a data source into a stream.
Streams can support
seeking. Seeking is the querying and modifying of the current position within a
stream.
Depending on the
underlying data source or repository, streams might support only some of these
capabilities. For example, NetworkStreams do not support seeking.
The CanRead, CanWrite, and CanSeek properties
of Stream and its derived classes determine the operations that
various streams support.
Classes Used for
File I/O
Directory provides static methods for creating,
moving, and enumerating through directories and subdirectories. TheDirectoryInfo class
provides instance methods.
DirectoryInfo provides
instance methods for creating, moving, and enumerating through directories and
subdirectories. The Directory class provides static methods.
DriveInfo provides
instance methods for accessing information about a drive
File provides
static methods for the creation, copying, deletion, moving, and opening of
files, and aids in the creation of a FileStream. The FileInfo class
provides instance methods.
FileInfo provides
instance methods for the creation, copying, deletion, moving, and opening of
files, and aids in the creation of a FileStream. The File class
provides static methods.
FileStream supports
random access to files through its Seek method. FileStream opens
files synchronously by default, but supports asynchronous operation as
well.
FileSystemInfo
is the abstract base class for FileInfo and DirectoryInfo.
Path provides
methods and properties for processing directory strings in a cross-platform
manner.
DeflateStream provides
methods and properties for compressing and decompressing streams using the
Deflate algorithm.
GZipStream provides
methods and properties for compressing and decompressing streams. By default,
this class uses the same algorithm as the DeflateStream class, but
can be extended to use other compression formats.
SerialPort provides
methods and properties for controlling a serial port file resource.
Classes Used for Reading
from and Writing to Streams
BinaryReader and BinaryWriter classes - Read
and write encoded strings and primitive data types from and to Streams.
StreamReader class- reads
characters from Streams, using Encoding to convert characters to
and from bytes.StreamReader has a constructor that attempts to ascertain
what the correct Encoding for a given Stream is, based on
the presence of an Encoding-specific preamble, such as a byte order
mark.
StreamWriter -writes
characters to Streams, using Encoding to convert characters to
bytes
StringReader- reads
characters from Strings. StringReader allows you to
treat Strings with the same API, so your output can be either
a Stream in any encoding or a String.
StringWriter -writes
characters to Strings. StringWriter allows you to treat Strings with
the same API, so your output can be either a Stream in any encoding
or a String.
TextReader- is
the abstract base class for StreamReader and StringReader. While
the implementations of the abstractStream class are designed for byte
input and output, the implementations of TextReader are designed for
Unicode character output.
TextWriter - is
the abstract base class for StreamWriter and StringWriter. While
the implementations of the abstractStream class are designed for byte
input and output, the implementations of TextWriter are designed for
Unicode character input.
Common I/O Stream
Classes
A BufferedStream is
a Stream that adds buffering to another Stream such as
a NetworkStream. (FileStream already has buffering internally, and
a MemoryStream does not need buffering.) . A BufferedStream can be composed around some types of streams in
order to improve read and write performance. A buffer is a block of bytes in
memory used to cache data, thereby reducing the number of calls to the
operating system.
A CryptoStream links
data streams to cryptographic transformations.
Although CryptoStream derives from Stream, it is not part of
the System.IO namespace, but is in
the System.Security.Cryptography namespace.
A MemoryStream is
a nonbuffered stream whose encapsulated data is directly accessible in memory.
This stream has no backing store and might be useful as a temporary buffer.
A NetworkStream represents
a Stream over a network connection.
Although NetworkStream derives from Stream, it is not part of
the System.IO namespace, but is in
the System.Net.Sockets namespace.
Common File IO Tasks
- Create a text file: System.IO.File
Provides static methods for the
creation, copying, deletion, moving, and opening of files, and aids in the
creation of FileStream objects.
2. Append File: File.AppendText Method
Creates a StreamWriter that appends
UTF-8 encoded text to an existing file.
3.Move file: File.Move
Moves a specified file to a new
location, providing the option to specify a
new file name.
4. Delete File:
File.Delete
Deletes the specified file.
5. Copy File: File.Copy
Copies an existing file to a new file.
Copy(String,String): Copies an existing
file to a new file. Overwriting a file of the same name is not allowed.
Copy(String,String,Boolean): Copies an
existing file to a new file. Overwriting a file of the same name is allowed.
6.Get the size of a
file: FileInfo.Length
Gets the size, in bytes, of the current
file.
7. Get the attributes
of a file: File.GetAttributes
Gets the FileAttributes of the file
on the path.
8. Set the attributes
of a file: File.SetAttributes
Sets the specified FileAttributes of the file on the specified path.
Sets the specified FileAttributes of the file on the specified path.
9. Determine whether a
file exists: File.Exists
Determines whether the specified file
exists.
10. Retrieve a file
extension: Path.GetExtension Method
Returns the extension of the specified
path string.
11. Retrieve the
fully qualified path of a file: Path.GetFullPath Method
Returns the absolute path for the
specified path string.
12. Retrieve the
file name and extension from a path: Path.GetFileName Method
Returns the file name and extension of
the specified path string.
13. Change the
extension of a file: Path.ChangeExtension Method
Changes the extension of a path string.
0 comments:
Post a Comment