Wednesday, November 6, 2013

Reading and Writing In Files using File Stream in C#

          In this article we are going to see how to open file for reading and writing, reading and writing in files are widely used in ErrorLog, activity log etc.

          As the name implies, it’s used to read data from text/ other files (audio, video).

System.IO namespace hosts the FileStream Class. FileStream Class instance method Read () reads the data from a file, and stores it into the array of bytes. The read task is carried out byte by byte. FileStream Class works with raw byte of data, and is common to work with different types of files as mentioned earlier.

It supports both synchronous or asynchronous data operations and tasks for reading and writing. For performance reason, it buffers input and output.

It supports random access to data. Seek () method allows positioning within stream data with internal pointer (byte offset reference point) for access.

Example

FileStream file = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            for (int i = 1; i <= 10; i++)
            {
                file.WriteByte((byte)i);
            }
            file.Position = 0;
            for (int i = 1; i <= 10; i++)
            {
                Console.Write(file.ReadByte() + " ");
            }
            file.Close();

More Example:

Normal Pattern:

using System.IO;
using System.Text;
class FileStreamExample
{
       public static void main()
       {
              FileStream fs = new FileStream("MyFile.txt",FileMode.Open);
              byte[] data = new byte[fs.Length];
              fs.Read(data, 0, (int)fs.Length);
             fs.Close();
             Console.Write( ASCIIEncoding.Default.GetString(data));
        }
}

                 In this example creating a byte array the length of the stream, using the Length property to properly size the array, and then passing it to the Read method.
The Read method fills the byte array with the stream data, in this case reading the entire stream into the byte array.

Note:
                  Streams/FileStream/MemoryStream must always be explicitly closed in order to release the resources they are using, which in this case is the file. Failing to explicitly close the stream can cause memory leaks, and it may also deny other users and applications access to the resource like failed to read/write/access.
                   
                 Alternative approach is to use disposable pattern, (because FileStream class implements IDisposable interface, which automatically dispose resources hold by it). It automatically release the resource hold by FileStream, In this approach we make use of using statement which release resource implicitly when it goes out of scope.

Example: (using disposable pattern)

class FileStreamExample
{
       public static void main()
       {
             byte[] data = new byte[fs.Length];
             using( FileStream fs = new FileStream("MyFile.txt",FileMode.Open))
             {
                    fs.Read(data, 0, (int)fs.Length);                   
             }
              Console.Write( ASCIIEncoding.Default.GetString(data));
        }
}

For More info refer FileStream in C#

No comments:

Post a Comment