From 7fcb6aa949bcfc9075a4bd4f64d03bf2e6816116 Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Thu, 27 Jun 2024 00:34:15 -0400 Subject: [PATCH] Create separate cookie web client --- Web/CookieWebClient.cs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Web/CookieWebClient.cs diff --git a/Web/CookieWebClient.cs b/Web/CookieWebClient.cs new file mode 100644 index 0000000..373fd52 --- /dev/null +++ b/Web/CookieWebClient.cs @@ -0,0 +1,40 @@ +using System; +using System.Net; + +#pragma warning disable SYSLIB0014 // 'WebClient.WebClient()' is obsolete +namespace SabreTools.RedumpLib.Web +{ + public class CookieWebClient : WebClient + { + // https://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class + private readonly CookieContainer _container = new(); + + /// + /// Get the last downloaded filename, if possible + /// + public string? GetLastFilename() + { + // If the response headers are null or empty + if (ResponseHeaders == null || ResponseHeaders.Count == 0) + return null; + + // If we don't have the response header we care about + string? headerValue = ResponseHeaders.Get("Content-Disposition"); + if (string.IsNullOrEmpty(headerValue)) + return null; + + // Extract the filename from the value + return headerValue.Substring(headerValue.IndexOf("filename=") + 9).Replace("\"", ""); + } + + /// + protected override WebRequest GetWebRequest(Uri address) + { + WebRequest request = base.GetWebRequest(address); + if (request is HttpWebRequest webRequest) + webRequest.CookieContainer = _container; + + return request; + } + } +} \ No newline at end of file