Reading and Writing Files using StreamReader in C#
Below is the Program showing use of StreamReader and StreamWriter to write the Characters in the Files.
using System;
using System.IO;
using static System.Console;
namespace StreamDemo
{
class Program
{
static string line="";
static void Main(string[] args)
{
StreamWriter st = new StreamWriter("D:\\Test.txt",true);
string [] cars = { "Audi", "Jeep","Jaguar" };
foreach(string s in cars)
{
st.WriteLine(s);
}
st.Close();
StreamReader sr = new StreamReader("D:\\Test.txt");
while ((line = sr.ReadLine()) != null)
{
WriteLine(line);
}
sr.Close(); ReadLine();
}
}
}
using System.IO;
using static System.Console;
namespace StreamDemo
{
class Program
{
static string line="";
static void Main(string[] args)
{
StreamWriter st = new StreamWriter("D:\\Test.txt",true);
string [] cars = { "Audi", "Jeep","Jaguar" };
foreach(string s in cars)
{
st.WriteLine(s);
}
st.Close();
StreamReader sr = new StreamReader("D:\\Test.txt");
while ((line = sr.ReadLine()) != null)
{
WriteLine(line);
}
sr.Close(); ReadLine();
}
}
}
Output
Explanation
Let's do the same program in different way.
using System;
using System.IO;
using static System.Console;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[5];
WriteLine("Enter names of fruits");
for (int i = 0; i < names.Length; i++)
{
names[i] = ReadLine();
}
using (StreamWriter sw = new StreamWriter("D:\\names2.txt"))
{
WriteLine("Fruit names are below");
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("D:\\names2.txt"))
{
while ((line = sr.ReadLine()) != null)
{
WriteLine(line);
}
}
ReadKey();
}
}
}
using System.IO;
using static System.Console;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[5];
WriteLine("Enter names of fruits");
for (int i = 0; i < names.Length; i++)
{
names[i] = ReadLine();
}
using (StreamWriter sw = new StreamWriter("D:\\names2.txt"))
{
WriteLine("Fruit names are below");
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("D:\\names2.txt"))
{
while ((line = sr.ReadLine()) != null)
{
WriteLine(line);
}
}
ReadKey();
}
}
}
Output
Explanation
Reading and Writing Files using StreamReader in C#
Reviewed by LanguageExpert
on
July 29, 2018
Rating:
No comments