FileStream - Read or Write Data Streams

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();
}
}
}


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.