Search code examples
vb.netrestsharp

VB.net RESTSharp AddFile using stream


I am trying to upload a file using RESTSharp in vb.net.

I am not able to complete this.

Following is the code I am trying.

Public Function CreateUploadFileRequest(ByVal path As String, ByVal filename As String, ByVal fileStream As Stream) As RestRequest
            Dim request = New RestRequest(Method.POST)
            request.Timeout = Integer.MaxValue
            request.Resource = "{version}/files/dropbox{path}"
            request.AddParameter("version", _version, ParameterType.UrlSegment)
            request.AddParameter("path", path, ParameterType.UrlSegment)
            request.AddParameter("file", filename)
            request.AddFile("file", fileStream, filename) '---I am wrong at this line
            Return request
        End Function

I found C# code, but not able to convert a particular line in vb.net

request.AddFile(FieldName, (s) =>
    {
        fileStream.CopyTo(s);
        fileStream.Flush();
    }, FileName, ContentType);

If I convert above into vb.net, then it does not work. Below is converted code.

request.AddFile("file", Function(s)
fileStream.CopyTo(s)
fileStream.Flush()
End Function, FileName, ContentType)

I also found one more line in c# but same is not working in vb.net after code convert.

[in C#] request.AddFile ("file", s => StreamUtils.CopyStream (fileStream, s), filename);

Converted to vb.net , [Not working]

[in vb.net] request.AddFile("file", Function(s) StreamUtils.CopyStream(fileStream, s), filename)

Solution

  • Following is working:

    dim ms as new MemoryStream()
    request.AddFile("file", ms.ToArray(), "123.pdf_or_whateverfilename")
    ms.Dispose()
    

    Comment: ms will be filled by the respective function in my code. In my case, it will be written by the pdf generator function.