I tried downloading the file using RestSharp, but the official method didn’t work.

1 minute read

I tried to download the file using RestSharp, but for some reason the file was not downloaded by the method described on the official website.
Therefore, I would like to keep it here as a memorandum.

Prerequisites

RestSharp is installed.

Event

On the official website, it was described as follows.
Working with Files | RestSharp

var tempFile = Path.GetTempFileName();
using var writer = File.OpenWrite(tempFile);

var client = new RestClient(baseUrl);
var request = new RestRequest("Assets/LargeFile.7z");
request.ResponseWriter = responseStream =>
{
    using (responseStream)
    {
        responseStream.CopyTo(writer);
    }
};
var response = client.DownloadData(request);

In the form of diverting this almost

var client = new RestClient(baseUrl);
var request = new RestRequest("Assets/LargeFile.7z");

,

var client = new RestClient("URL of the content");
var request = new RestRequest();

When I changed it to and executed it, response became null and returned, and the download failed.
Of course, the URL wasn’t wrong.
(I personally wondered if it wasn’t good to pass the URL of the entire content to baseUrl, but I wasn’t sure what the real cause was.)

Solution

As a result of various investigations, I succeeded in downloading the file by the following method.

var client = new RestClient("URL of the content");
var response = client.DownloadData(new RestRequest(Method.GET));

By the way, the variable response contains a byte array (the substance of the file data).
Therefore, you can save it locally by writing the file using File.WriteAllBytesAsync etc.

File.WriteAllBytesAsync("Local save destination", response);

Summary

There are other methods besides the official method for downloading files using RestSharp, so I have summarized them.
It turns out that the official method doesn’t always work.
If possible, it is more reliable to use the official method, so there is no doubt, but I would like to use it flexibly.
(It’s a pity that RestSharp doesn’t have a lot of official documentation.)

Reference URL