20. FileStream yordamida matnli faylga ma'lumotlarni o'qish va yozish uchun C# dasturini amalga oshiring.
Javob:
using System.IO;
class Program {
static void Main(string[] args) {
// Path to text file
string path = @"C:\example.txt";
// Write data to text file
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter writer = new StreamWriter(fs)) {
// Data to be written
string data = "Hello, World!";
writer.Write(data);
}
}
// Read data from text file
using (FileStream fs = new FileStream(path, FileMode.Open)) {
using (StreamReader reader = new StreamReader(fs)) {
// Output read data (Hello, World!)
System.Console.WriteLine(reader.ReadToEnd());
}
}
}
}
Izoh: Bu kod “Salom, dunyo!” matnini yozadi. C:\example.txt manzilida joylashgan matn fayliga, so‘ngra uni qayta o‘qiydi va konsolda chop etadi.
51. Ma'lumotlar oqimi yordamida ma'lumotlarni shifrlaydigan va faylga yozadigan C# dasturini yarating.
Javob:
using System;
using System.IO;
using System.Security.Cryptography;
class Program
{
static void Main()
{
string plainText = "Hello, world!";
string filePath = @"C:\secret.txt";
byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (FileStream fsEncrypt = new FileStream(filePath,
FileMode.Create))
{
using (CryptoStream csEncrypt = new CryptoStream(fsEncrypt,
encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
}
}
}
}
Do'stlaringiz bilan baham: |