Harry Potter and the Sorcerer's Stone


Katta hajmdagi faylni qismlarga bo'lib yuklab olish uchun ma'lumotlar oqimidan foydalanadigan C# dasturini yarating


Download 192.49 Kb.
bet28/62
Sana17.06.2023
Hajmi192.49 Kb.
#1535967
1   ...   24   25   26   27   28   29   30   31   ...   62
Bog'liq
Algaritim amaliy-2

59. Katta hajmdagi faylni qismlarga bo'lib yuklab olish uchun ma'lumotlar oqimidan foydalanadigan C# dasturini yarating.
Javob:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
string url = "https://example.com/largefile.zip";
string outputFile = "output.zip";
int blockSize = 1024 * 1024; // 1 MB

WebRequest request = WebRequest.Create(url);


long fileSize = request.GetResponse().ContentLength;
request.Abort();

Console.WriteLine($"Downloading {fileSize / (1024 * 1024)} MB...");

using (FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
{
for (long i = 0; i < fileSize; i += blockSize)
{
long remainingBytes = fileSize - i;
int currentBlockSize = remainingBytes < blockSize ? (int)remainingBytes : blockSize;

request = WebRequest.Create(url);


request.Method = WebRequestMethods.Http.Get;
request.AddRange(i, i + currentBlockSize - 1);

using (WebResponse response = request.GetResponse())


{
using (Stream inputStream = response.GetResponseStream())
{
inputStream.CopyTo(outputStream);
}
}
}
}

Console.WriteLine("Done!");


}
}
Ushbu kod katta faylni URL manzilidan qismlarga bo'lib yuklab oladi, har bir qismi belgilangan blok o'lchamiga ega. U faylning muayyan qismini yuklab olish uchun Range sarlavhasini belgilab, serverga HTTP GET soʻrovlarini yuborish uchun WebRequest sinfidan foydalanadi. Keyin dastur har bir qismni oldingi qismga qo'shib, fayl oqimiga yozadi. Nihoyat, dastur oqimni yopadi va yuklab olish tugallanganligini bildiruvchi xabarni ko'rsatadi.
Siz ushbu kodni url, outputFile va blockSize oʻzgaruvchilarni oʻz ehtiyojlaringizga moslashtirish orqali oʻzgartirishingiz mumkin. E'tibor bering, misol kodida server Range sarlavhasini qo'llab-quvvatlaydi va faylni parallel qismlarga yuklab olish mumkin. Ba'zi serverlar bu xususiyatni qo'llab-quvvatlamasligi mumkin, shuning uchun kodni mos ravishda o'zgartirishingiz kerak bo'lishi mumkin.

Download 192.49 Kb.

Do'stlaringiz bilan baham:
1   ...   24   25   26   27   28   29   30   31   ...   62




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