.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# StreamWriter
C# StreamWriter
C# StreamWriter class is used to write characters to a stream in specific encoding. It inherits TextWriter class. It provides overloaded write() and writeln() methods to write data into file.
C# StreamWriter example
Let's see a simple example of StreamWriter class which writes a single line of data into the file.
using System;
using System.IO;
public class StreamWriterExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\output.txt", FileMode.Create);
StreamWriter s = new StreamWriter(f);
s.WriteLine("hello c#");
s.Close();
f.Close();
Console.WriteLine("File created successfully...");
}
}
using System.IO;
public class StreamWriterExample
{
public static void Main(string[] args)
{
FileStream f = new FileStream("e:\\output.txt", FileMode.Create);
StreamWriter s = new StreamWriter(f);
s.WriteLine("hello c#");
s.Close();
f.Close();
Console.WriteLine("File created successfully...");
}
}
Output:
File created successfully...
Now open the file, you will see the text "hello c#" in output.txt file.
output.txt:
hello c#