1- misol. uqish.txt fayldan ikkita sonni o’qib, ularni yig’indisini yozish.txt fayliga
yozish dasturini ko’rib chiqamiz.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1 {
class Program {
37
static void Main(string[] args) {
StreamWriter yozish = new StreamWriter("d:\\yozish.txt");
StreamReader uqish = new StreamReader("d:\\uqish.txt");
yozish.WriteLine(int.Parse(uqish.ReadLine()) +
int.Parse(uqish.ReadLine()));
yozish.Close();
uqish.Close();
} }
Dastur natijasi: dasturni ishlatishdan oldin uqish.txt faylda 2 ta son kiritish kerak,
so’ng dastur ikkita sonni o’qib, ularni yig’indisini yozish.txt fayliga yozadi.
Natijani ko’rish uchun yozish.txt faylni ochib ko’rish kerak
2-misol. fayl davomidan ma’lumotlarni yozish.
class Program {
static void Main(string[] args){
/*textFile.txt faylining yangi satridan "yangi satr" so'zini qo'shadi
agar bu fayl bo'lmasa o'zi yaratib "yangi satr" so'zini qo'shadi*/
StreamWriter a;
a = File.AppendText("d:\\textFile.txt");
a.WriteLine("yangi satr");
a.Close();
} }
3- misol. fayldan ma’lumotlarni bitta bitta belgi orqali o’qish va chiqarish.
class Program {
[STAThread]
static void Main(string[] args) {
StreamReader uqish;
try
{
uqish = new StreamReader("d:\\textFile.txt");
}
38
catch {
Console.WriteLine("Faylni ochishda xatolik bor");
Console.ReadKey();
return; }
int ch;
while ((ch = uqish.Read()) != (-1))
{
Console.WriteLine((char)ch);
}
Console.ReadKey();
} }
4- misol. Faylda ma’lumotlarni binar yozish va o’qish.
class Program {
static void Main(string[] args) {
FileStream a = new FileStream("d:\\a.txt", FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(a);
//faylga ma'lumotlarni yozamiz
for (int i = 1; i
w.Write( (int) i); }
//faylni yopish
w.Close();
a = new FileStream("d:\\a.txt", FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(a);
// fayldan ma’lumotlarni o’qiymiz
for (int i = 1; i
Console.WriteLine(r.ReadInt32()); }
r.Close();
Console.ReadKey();
} }
5- misol. fayldan ma’lumotlarni satrma - satr o’qish.
39
class Program {
static void Main(string[] args){
FileStream a = new FileStream("d:\\textFile.txt", FileMode.Open,
FileAccess.Read);
StreamReader b = new StreamReader(a);
string s;
while ((s = b.ReadLine()) != null){
Console.WriteLine(s); }
b.Close();
Console.ReadKey();
} }
|