Sunday, March 9, 2014

Get StreamWriter in C#

DriveInfo , DirectoryInfo , FileInfoStreamReader , StreamWriter

StreamWriter in FileInfo

  • To write / read the content to / write the file, you require file streams.
  • A file stream acts as a pointer for the file, which contains the memory address of the file on the disc.
There are two types of file streams.
1)  Reading Streams
2)  Writing Streams
API: System.IO.StreamWriter (to write the content into the file)

Writing content to the file
Import the API
using System.IO;
Create the stream writer object
StreamWriter sw = new StreamWriter(file name);
Write the content
sw.Write(content here);
Close the Writer

Program for StreamWriter                                                                

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileWriteDemo
class Program
static void Main(string[] args)
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (!fobj.Exists)
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();
StreamWriter sw = new StreamWriter(filepath);
Console.WriteLine("\nWritten successfully!");
Console.WriteLine("File already exists."); 
DriveInfo , DirectoryInfo , FileInfoStreamReader , StreamWriter