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?
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));
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With