2

This question is not answered yet in Stack Overflow and it's not duplicated

I have a code exactly like this, try to upload files with RestSharp library.

Problem :
But the problem is upload files fill the memory (RAM) and it's bad or got error on large files.

var client = new RestClient("https://example.com/api/");
var request = new RestRequest("file/upload", Method.POST);
string filePath = @"C:\LargeFile.mkv";

client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = true);

request.AddHeader("Content-Type", "multipart/form-data");

request.AddParameter("access_token", "exampleToken");

request.AddFileBytes("upload_file", File.ReadAllBytes(filePath), Path.GetFileName(filePath), MimeMapping.GetMimeMapping(filePath));

client.ExecuteAsync(request, response =>
{
    Console.WriteLine(response.Content);
});

Note: I don't find a working way to do this without filling RAM, I know that it must use stream types or byte arrays, but I can't do it.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Root
  • 2,269
  • 5
  • 29
  • 58
  • https://stackoverflow.com/questions/6865890/how-can-i-read-stream-a-file-without-loading-the-entire-file-into-memory is this not what you are looking for – work monitored Jul 08 '19 at 17:58
  • Thanks, It seems to be, but the biggest problem is how to implement that into RestSharp addFile or addFileBytes methods ? – Root Jul 08 '19 at 21:41

1 Answers1

1

You need to use the AddFile overload that accepts the stream writer callback:

IRestRequest AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);

It has a drawback that you must specify the file size explicitly because there's no way for RestSharp to know in advance what you will write to the stream and the file size must be included to the ContentLength request header.

When using the stream writer, your function will be called with the request file stream, so you can just write to it real-time, without loading the file to memory first.

Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83