StreamReader এবং StreamWriter ক্লাসগুলো টেক্সট ফাইল থেকে পড়া এবং ডেটা লেখার জন্য ব্যবহৃত হয়।
টেক্সট ফাইল পড়া
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// StreamReader ইনস্ট্যান্স তৈরি করুন ফাইল পড়ার জন্য
// using স্টেটমেন্ট StreamReader ক্লোজও করে
using (StreamReader sr = new StreamReader("d:/new.txt"))
{
string line;
// ফাইল থেকে লাইন পড়ুন এবং প্রদর্শন করুন
// ফাইল শেষ পর্যন্ত
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
টেক্সট ফাইলে লেখা
উদাহরণ
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] { "Jack", "Tom" };
using (StreamWriter sw = new StreamWriter("students.txt"))
{
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// ফাইল থেকে প্রতিটি লাইন পড়ুন এবং দেখান
string line = "";
using (StreamReader sr = new StreamReader("students.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
আউটপুট
Jack Tom