Harry Potter and the Sorcerer's Stone


C# yordamida fayldan ikkilik ma'lumotlarni o'qing


Download 192.49 Kb.
bet43/62
Sana17.06.2023
Hajmi192.49 Kb.
#1535967
1   ...   39   40   41   42   43   44   45   46   ...   62
Bog'liq
Algaritim amaliy-2

33. C# yordamida fayldan ikkilik ma'lumotlarni o'qing.
Javob:
Siz C# tilidagi fayldan ikkilik ma'lumotlarni o'qish uchun FileStream sinfidan foydalanishingiz mumkin.
byte[] buffer = new byte[1024];
using (var fileStream = new FileStream("filename.bin", FileMode.Open))
{
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
// process the bytes read from the file
// ...
}
}
Ushbu kod "filename.bin" fayli uchun FileStream misolini yaratadi va undagi ma'lumotlarni bir vaqtning o'zida 1024 baytlik buferga o'qiydi. Keyin kerakli ma'lumotlarni qayta ishlashingiz mumkin. Tugallangach, FileStream obyektini utilizatsiya qilishni unutmang.
34. C# dan foydalanib faylga seriyali ma'lumotlarni yozing va o'qing.
Javob:
C#-da faylga ketma-ketlashtirilgan ma'lumotlarni yozish uchun siz StreamWriter sinfidan foydalanishingiz mumkin.
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
// create an instance of the object you want to serialize
MySerializableObject obj = new MySerializableObject();
// create a binary formatter
BinaryFormatter formatter = new BinaryFormatter();
// open a file stream for writing
FileStream stream = new FileStream("filename.bin", FileMode.Create);
// serialize the object and write it to the file stream
formatter.Serialize(stream, obj);
// close the file stream
stream.Close();
Ushbu kod ketma-ketlashtiriladigan obyekt, ikkilik formatlovchi va yozish uchun fayl oqimining namunasini yaratadi. Keyin formatlovchi yordamida ob'ektni seriyalashtiradi va ketma-ketlashtirilgan ma'lumotlarni fayl oqimiga yozadi. Nihoyat, u fayl oqimini yopadi.
Seriallashtirilgan maʼlumotlarni fayldan qayta oʻqish uchun siz StreamReader sinfidan foydalanishingiz mumkin. Mana bir nechta namuna kodi:
// open a file stream for reading
FileStream stream = new FileStream("filename.bin", FileMode.Open);
// deserialize the object and read it from the file stream
MySerializableObject obj = formatter.Deserialize(stream) as MySerializableObject;
// close the file stream
stream.Close();
Ushbu kod o'qish uchun fayl oqimini ochadi, formatlashtiruvchi yordamida ob'ektni seriyadan chiqaradi va fayl oqimidan seriyasizlashtirilgan ma'lumotlarni o'qiydi. Nihoyat, u fayl oqimini yopadi.

Download 192.49 Kb.

Do'stlaringiz bilan baham:
1   ...   39   40   41   42   43   44   45   46   ...   62




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