Files
2026-02-16 17:12:34 -05:00

48 lines
1.5 KiB
C#

using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using Serilog;
namespace TvSyncApp
{
public class Downloader
{
private static readonly HttpClient _httpClient = new HttpClient();
public void Download(string url, string outputDir, string outputFile, ILogger log)
{
try
{
// log.Information("Downloading {Url} to {OutputFile}", url, outputFile);
// Ensure the output directory exists
Directory.CreateDirectory(outputDir);
// Get JSON content as string
var response = _httpClient.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
string jsonString = response.Content.ReadAsStringAsync().Result;
// Parse and pretty-print JSON
var jsonDoc = JsonDocument.Parse(jsonString);
var formattedJson = JsonSerializer.Serialize(jsonDoc.RootElement, new JsonSerializerOptions
{
WriteIndented = true
});
// Write to file
string filePath = Path.Combine(outputDir, outputFile);
File.WriteAllText(filePath, formattedJson);
//log.Information("Downloaded and formatted {OutputFile} successfully.", outputFile);
}
catch (Exception ex)
{
log.Error(ex, "Failed to download {OutputFile} from {Url}", outputFile, url);
}
}
}
}