Create separate cookie web client

This commit is contained in:
Matt Nadareski
2024-06-27 00:34:15 -04:00
parent f22b1b036b
commit 7fcb6aa949

40
Web/CookieWebClient.cs Normal file
View File

@@ -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();
/// <summary>
/// Get the last downloaded filename, if possible
/// </summary>
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("\"", "");
}
/// <inheritdoc/>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest webRequest)
webRequest.CookieContainer = _container;
return request;
}
}
}