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


FileStream yordamida matnli faylga ma'lumotlarni o'qish va yozish uchun C# dasturini amalga oshiring


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

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);
}
}
}
}
}
}


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