Witam,
mam prośbę o pomoc w następującej kwestii. Na wstępie zaznaczam, że jest początkujący w C#.
Chciałem napisać apkę, która pobierać będzie z użyciem HttpClient plik z określonego adresu WWW i będzie ten plik zapisywać w określonej lokalizacji lokalnej na komputerze.
Na stronie Code4it podanej w kodzie poniżej znalazłem kod, który powinien na to pozwolić. Niestety nie wiem jak go wywołać. Wiersz var task = Task Run... zwraca błąd "CS0120 An object reference is required for the non-static field, method, or property ".
Będę wdzięczny za pomoc!
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpClientTest
{
class Program
{
static void Main(string[] args)
{
string sourceURL = String.Format("https://plikplaski.mf.gov.pl/pliki//20240129.7zip");
string targetDirectory = String.Format(@"D:\Users\TestUser\Downloads\X\");
string targetFileName = String.Format(@"20240129.7zip");
//var task = Task.Run(() => DownloadAndSave(sourceURL, targetDirectory, targetFileName)); Jak wywołać DownloadAndSave
task.Wait();
}
// the following code is from https://www.code4it.dev/blog/download-and-save-files/
async Task DownloadAndSave(string sourceFile, string destinationFolder, string destinationFileName)
{
Stream fileStream = await GetFileStream(sourceFile);
if (fileStream != Stream.Null)
{
await SaveStream(fileStream, destinationFolder, destinationFileName);
}
}
async Task<Stream> GetFileStream(string fileUrl)
{
HttpClient httpClient = new HttpClient();
try
{
Stream fileStream = await httpClient.GetStreamAsync(fileUrl);
return fileStream;
}
catch (Exception ex)
{
return Stream.Null;
}
}
async Task SaveStream(Stream fileStream, string destinationFolder, string destinationFileName)
{
if (!Directory.Exists(destinationFolder))
Directory.CreateDirectory(destinationFolder);
string path = Path.Combine(destinationFolder, destinationFileName);
using (FileStream outputFileStream = new FileStream(path, FileMode.CreateNew))
{
await fileStream.CopyToAsync(outputFileStream);
}
}
}
}