49. Ma'lumotlar oqimi yordamida veb-serverdan faylni yuklab olish uchun C#
dasturini yozing.
Javob:
C# tilida ma'lumotlar oqimi yordamida veb-serverdan faylni yuklab olish uchun:
using System;
using System.IO;
using System.Net;
class Program {
static void Main(string[] args) {
string url = "your_url_here";
string fileName = "your_file_name_here";
string destinationPath = "your_destination_path_here";
try {
using (Stream stream = File.Create(destinationPath + '\\' + fileName)) {
WebClient client = new WebClient();
Stream dataStream = client.OpenRead(url);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = dataStream.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, bytesRead);
}
dataStream.Close();
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.WriteLine("File downloaded successfully!");
}
}
50. Mavjud C# dasturini buferlanmagan ma'lumotlar oqimi o'rniga buferlangan ma'lumotlar oqimidan foydalanish uchun o'zgartiring.
Javob:
using System;
using System.IO;
class Program {
static void Main(string[] args) {
string outputFilePath = "output.txt";
try {
// Open a buffered stream for writing to output.txt
using (StreamWriter writer = new StreamWriter(outputFilePath)) {
// Change Console.WriteLine to writing to the buffered stream
Console.SetOut(writer);
Console.WriteLine("Hello, world!");
Console.WriteLine("This program is now buffered.");
}
Console.WriteLine("This text will not be buffered because the using block has ended.");
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
Bu “Salom, dunyo!” deb yozadi. va "Ushbu dastur endi buferlangan." dasturni ishga tushirganingizda output.txt ga. Esda tutingki, foydalanish bloki tugaganidan keyin Konsolga yozilgan har qanday matn buferlanmaydi, chunki oqim yopilgan.
Do'stlaringiz bilan baham: |