Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebClient.UploadFile pass upload file as stream

I am trying to use WebClient.UploadFile in my project to post file to server. WebClient.UploadFile accept file name uri as parameter but I would like to pass file stream instead of file name uri. Is that possible with WebClient?

like image 590
Tomas Avatar asked Jan 16 '12 09:01

Tomas


2 Answers

Here are some examples that shows how to write stream to the specified resource using WebClient class:

Using WebClient.OpenWrite:

using (var client = new WebClient())
{
     var fileContent = System.IO.File.ReadAllBytes(fileName);
     using (var postStream = client.OpenWrite(endpointUrl))
     {
         postStream.Write(fileContent, 0, fileContent.Length);
     }
 }

Using WebClient.OpenWriteAsync:

using (var client = new WebClient())
{
     client.OpenWriteCompleted += (sender, e) =>
     {
        var fileContent = System.IO.File.ReadAllBytes(fileName);
        using (var postStream = e.Result)
        {
            postStream.Write(fileContent, 0, fileContent.Length);    
        }
     };
     client.OpenWriteAsync(new Uri(endpointUrl));
 }
like image 56
Vadim Gremyachev Avatar answered Jan 01 '23 19:01

Vadim Gremyachev


You should be able to use the methods WebClient.OpenWrite and OpenWriteAsync to send a stream back to your server.

If you use the later then subscribe to OpenWriteCompleted and use e.Result as the stream to CopyTo.

like image 35
poupou Avatar answered Jan 01 '23 20:01

poupou