Si desea mantener las transmisiones en todas partes y evitar asignar grandes matrices de bytes, lo cual es una buena práctica (por ejemplo, si planea publicar archivos grandes), aún puede hacerlo con una versión derivada de WebClient. Aquí hay un código de muestra que lo hace.
using (var client = new WebClientWithResponse())
{
using (var stream = client.OpenWrite(myUrl))
{
// open a huge local file and send it
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
file.CopyTo(stream);
}
}
// get response as an array of bytes. You'll need some encoding to convert to string, etc.
var bytes = client.Response;
}
Y aquí es el cliente Web personalizada:
public class WebClientWithResponse : WebClient
{
// we will store the response here. We could store it elsewhere if needed.
// This presumes the response is not a huge array...
public byte[] Response { get; private set; }
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
var httpResponse = response as HttpWebResponse;
if (httpResponse != null)
{
using (var stream = httpResponse.GetResponseStream())
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
Response = ms.ToArray();
}
}
}
return response;
}
}
Véase también http://stackoverflow.com/questions/1694388/webclient-vs-httpwebrequest-httpwebresponse. – DuckMaestro