Reader Level:

FileStream : Read or Write Data Streams

By Mahesh Chand on Dec 13, 2000
FileStream class can be used to read/write data to a file with the help of StreamReader and StreamWriter classes.

Tools Used: Visual C# .NET

The FileStream class is derived from Stream class. This class can be used for reading from and writing to files such as bytes, characters, strings, and other data-type values to a file. Other class I have used in this sample is StreamWriter. The StreamWriter class's Write and WriteLine members write to a file.

In this sample code, I have used FileStream class to create a text file and StreamWrite to write text to the text file.

namespace mcFileStream
using System;
using System.IO;
public class mcLogFile
public static void Main(String[] args)
// Create a text file C:\temp\mcb.txt
FileStream fs = new FileStream(@"c:\temp\mcb.txt" , FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new StreamWriter(fs);
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : ");
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine(" First Line : Data is first line \n");
m_streamWriter.WriteLine(" This is next line in the text file. \n ");
// Read from the file using StreamReader class
// StreamReader m_streamReader = new StreamReader(fs);
// string str = m_streamReader.ReadLine();

Mahesh Chand
Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more



Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
Infragistics jQuery Controls

Trending up