Monday, January 23, 2012

FileStream in .Net (C#)


FileStream class can be used to read / write data to files. FileStream class is derived from abstract Stream class. FileStream supports synchronous or asynchronous read/write operations. By default FileStream opens file synchronously. FileStream also supports random access using seek method. You can open file by passing string file name (path) to FileStream constructor. You can also specify FileMode and FileAccess along with filename. FileMode specifies how file should open while FileAccess specifies file should open for Read or Write or Both operations


Below is the details about FileMode and FileAccess enum.

FileModes
Description
Open
Opens an existing file for writing.
OpenOrCreate
Opens an existing file if not found creates new.
Create
Creates new file, if exists it will be overwrite.
CreateNew
Creates new file, if already exists throws an error.
Append
Opens an existing file and seek to end. If not exists creates new file.

FileAccess
Description
Read
Allows only read from file.
Write
Allows only write to file.
ReadWrite
Allows read/write to file.

Below examples shows how we can use FileModes and FileAccesss with FileStream.

//Opens an existing file for read operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Read);

//Opens an existing file for write operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Write);

//Opens an existing file for read/write operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.ReadWrite);

//creates new file, if exists it will be overwritten
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Create);

//Opens an existing file and seek to end. if not exists creates new file.
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Append);

Read/Write data using FileStream Read/Write methods.

//Write data
using (FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Create, FileAccess.Write))
{
    string start = "Hello World!!!";

    byte[] byts = System.Text.Encoding.ASCII.GetBytes(start);

    fs.Write(byts, 0, byts.Length);
}

//Read data
using (FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Read))
{
    byte[] byts = new byte[1024];
    while (fs.Read(byts, 0, byts.Length) > 0)
    {
        Console.WriteLine(System.Text.Encoding.ASCII.GetString(byts));
    }
}

Output –



See Also - 

No comments:

Post a Comment