Algaritim: Savol-javoblar C# dasturlash tilida oqim nima? Javob


Ma'lumotlar oqimi yordamida C# dasturini faylga ma'lumotlar yozish va o'qish uchun kod yozing


Download 66.18 Kb.
bet15/18
Sana05.05.2023
Hajmi66.18 Kb.
#1429940
1   ...   10   11   12   13   14   15   16   17   18
Bog'liq
Algaritim amaliy-2

55. Ma'lumotlar oqimi yordamida C# dasturini faylga ma'lumotlar yozish va o'qish uchun kod yozing.
Javob:
using System.IO;
// Faylga yozish
StreamWriter sw = new StreamWriter("file.txt");
sw.WriteLine("Ma'lumotlar faylda saqlandi.");
sw.Close();
// Fayldan o'qish
StreamReader sr = new StreamReader("file.txt");
string line = sr.ReadLine();
sr.Close();
Console.WriteLine(line);
56. Mavjud C# dasturini oddiy dastur o'rniga GZIP ma'lumotlar oqimidan foydalanish uchun o'zgartiring.
Javob:
using System.IO;
using System.IO.Compression;

// Matn ma'lumotni GZIP ko'rinishiga o'tkazish


string text = "Ma'lumotlar";
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
{
zipStream.Write(buffer, 0, buffer.Length);
}

// GZIP ma'lumotni faylga yozish


File.WriteAllBytes("compressed.gz", ms.ToArray());

// Fayldan GZIP ma'lumotni o'qish va matngacha qaytarish


byte[] compressedData = File.ReadAllBytes("compressed.gz");
ms = new MemoryStream(compressedData);
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress))
{
byte[] decompressedBuffer = new byte[1024];
using (MemoryStream decompressedMs = new MemoryStream())
{
int read;
while ((read = zipStream.Read(decompressedBuffer, 0, decompressedBuffer.Length)) > 0)
{
decompressedMs.Write(decompressedBuffer, 0, read);
}

string decompressedText = Encoding.UTF8.GetString(decompressedMs.ToArray());


Console.WriteLine(decompressedText);
}
}
57. Ma'lumotlar oqimi yordamida SQLite ma'lumotlar bazasidan ma'lumotlarni o'qiydigan va uni formatlangan tarzda ko'rsatadigan C# dasturini yozing.
Javob:
using System.Data.SQLite;
// Ma'lumotlar bazasiga ulanish
SQLiteConnection connection = new SQLiteConnection("Data Source=myDatabase.db;Version=3;");
connection.Open();
// SQL so'rovni tuzish va bajargan natijani qaytarish
string sql = "SELECT * FROM MyTable";
SQLiteCommand command = new SQLiteCommand(sql, connection);
SQLiteDataReader reader = command.ExecuteReader();
// Natijalarni ko'rib chiqish
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
DateTime date = reader.GetDateTime(2);

Console.WriteLine($"ID: {id}, Name: {name}, Date: {date}");


}
// Ma'lumotlar bazasiga aloqani yopish
reader.Close();
command.Dispose();
connection.Close();

Download 66.18 Kb.

Do'stlaringiz bilan baham:
1   ...   10   11   12   13   14   15   16   17   18




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling