Using HttpWebRequest, I can call XDocument.Save() to write directly to the request stream:
XDocument doc = ...;
var request = (HttpWebRequest)WebCreate.Create(uri);
request.method = "POST";
Stream requestStream = request.GetRequestStream();
doc.Save(requestStream);
Is it possible to do the same thing with HttpClient? The straight-forward way is
XDocument doc = ...;
Stream stream = new MemoryStream();
doc.Save(stream);
var content = new System.Net.Http.StreamContent(stream);
var client = new HttpClient();
client.Post(uri, content);
But this creates another copy of the XDocument in the MemoryStream.
XDocument.Save()expects aStreamthat can be written to.StreamContentexpects a stream that can be read. So, you can use a twoStreams, where one acts as as a forwarder for the other one. I don’t think such type exists in the framework, but you can write one yourself:Unfortunately, you can’t read and write to those streams at the same time from the same thread. But you can use
Taskto write from another thread: