Untitled
unknown
csharp
3 years ago
1.9 kB
40
Indexable
public static void DownloadModpack(string url, string directory, ProgressBar loading)
{
string filename = RequestHandler.FormatUrlToFilename(url) + ".download";
string parentDirectory = InternalFileManager.INSTANCE.QueryDirectoryPath(directory, true);
// Open a WebStream that downloads the file chunks, and a filestream that writes the chunks to the file.
using (HttpResponseMessage response = ClientInstance.GetAsync(url, HttpCompletionOption.ResponseContentRead).Result)
using (Stream contentStream = response.Content.ReadAsStreamAsync().Result)
using (FileStream fileStream = File.Create(Path.Combine(parentDirectory, filename)))
{
byte[] buffer = new byte[1024 * 3072]; // Sets the buffer (Amount of bytes read per iteration)
// Request the the size in bytes for the file
Logging.INSTANCE.LogAll("Requesting file size...", "DOWNLOADER");
long.TryParse(response.Content.Headers.First(h => h.Key.Equals("Content-Length")).Value.First(), out long contentSize);
Logging.INSTANCE.LogAll("File size: " + contentSize + " bytes", "DOWNLOADER");
while (true)
{
// Reads a chunk of bytes from the contentStream
var byteChunk = contentStream.ReadAsync(buffer, 0, buffer.Length).Result;
// Write the chunk to the file and update the loading bar
fileStream.WriteAsync(buffer, 0, byteChunk);
loading.Value = (int) (fileStream.Length / (double) contentSize * 100.0D);
loading.Text = $@"Downloading... {loading.Value}%";
if (byteChunk == 0) break; // If the chunk is empty, break.
}
}Editor is loading...