cheader
cheader

Reputation: 11

importing cookies from a web browser to download files c#

i am trying to download osu! beatmaps using the link for example https://osu.ppy.sh/beatmapsets/1012634 i want to do the same as clicking the download button.

i tried the API and sending a request to https://osu.ppy.sh/beatmapsets/1012634/download and downloading the response but it didn't work i think i should import cookies like this but i am not sure how to do that in c#

here is the code i have so far:

using System;
using System.Net;
using System.IO;

public static class MangoDownload
{
    public static void Main(string[] args)
    {
        var wc = new CookieAwareWebClient();
        string downloadDir = Path.Combine(@"C:\Users\username\Downloads", "map.osz");
        string url = "https://osu.ppy.sh/beatmapsets/1012634/download";

        wc.Headers.Add("User-Agent", "agent");
        Set a cookie if necessary
        wc.Headers.Add(HttpRequestHeader.Cookie, "your_cookie_here");

        try
        {
            wc.DownloadFile(url, downloadDir);
            Console.WriteLine("Download successful!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error downloading file: {ex.Message}");
        }

        Console.WriteLine("That's it!");
        Console.ReadKey();
    }

    public class CookieAwareWebClient : WebClient
    {
        private readonly CookieContainer m_container = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            HttpWebRequest webRequest = request as HttpWebRequest;
            if (webRequest != null)
            {
                webRequest.CookieContainer = m_container;
            }
            return request;
        }
    }
}

any help would be greatly appreciated.

Upvotes: 0

Views: 45

Answers (0)

Related Questions