Created
December 1, 2021 16:54
-
-
Save dupdob/c046134ffde96b0f0fc5a82b09f53600 to your computer and use it in GitHub Desktop.
Get your input data for Advent Of Code and cache it locally in a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace AocHelpers | |
{ | |
/// <summary> | |
/// Returns AdventOfCode input data, locally cached | |
/// </summary> | |
/// <param name="pathName">Path were the data are stored</param> | |
/// <param name="sessionId">session identifier (use your own id, stored in AoC session cookie)</param> | |
/// <param name="day">Day number (1-24)</param> | |
/// <returns>Your input data.</returns> | |
/// <remarks>The first call for a given will get the data from AoC site and cache it locally. If the file | |
/// exist, returns the file content. | |
/// </remarks> | |
static string GetAocInputFile(string pathName, string sessionId, int day) | |
{ | |
string input; | |
var fileName = Path.Combine( pathName, $"AocDay{day}-MyInput.txt"); | |
if (!File.Exists(fileName)) | |
{ | |
var uri = new Uri($"https://adventofcode.com/2021/day/{day}/input"); | |
using var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() }; | |
using var client = new HttpClient(handler); | |
// add our identifier to the request | |
handler.CookieContainer.Add(new Cookie("session", | |
sessionId, "/", ".adventofcode.com")); | |
// get our data | |
input = client.GetStringAsync(uri).Result; | |
// save it for the next run | |
File.WriteAllText(fileName, input); | |
} | |
else | |
{ | |
// get the data we already fetched | |
input = File.ReadAllText(fileName); | |
} | |
return input; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment