Reader Level:
ARTICLE

FileStream : Read or Write Data Streams

On December 13, 2000 Articles | C# Programming
FileStream class can be used to read/write data to a file with the help of StreamReader and StreamWriter classes.
  • 1
  • 0
  • 240383

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 ");
m_streamWriter.Flush();
// Read from the file using StreamReader class
// StreamReader m_streamReader = new StreamReader(fs);
// string str = m_streamReader.ReadLine();
}
}
}

Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  M...

  • 1rank
  • 71M readers
  • 9times
COMMENT USING

Trending up