Search code examples
c#asp.netxmlwebclientmemorystream

Send XML via WebClient Post using MemoryStream


I am trying to send an XML file that I created in my memorystream. The problem comes in when I try to use UploadFile and get the error of Invalid Arguments. My question is, is there anyway I can use my memorystream that I created with WebClient.UploadFile to send the file or do I need to do this some other way?

string firstname = Request.Headers["firstname"].ToString();
string lastname = Request.Headers["lastname"].ToString();
string organization = Request.Headers["organization"].ToString();
string phone = Request.Headers["phone"].ToString();

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
using (XmlWriter xml = XmlWriter.Create(ms, settings))
{
    xml.WriteStartDocument();
    xml.WriteStartElement("List");
    xml.WriteWhitespace("\n");

    xml.WriteStartElement("Employee");
    {
        xml.WriteElementString("First", firstname);
        xml.WriteElementString("Last", lastname);
        xml.WriteWhitespace("\n");
        xml.WriteElementString("Organization", organization);
        xml.WriteElementString("Phone", phone);
    }

    xml.WriteEndElement();
    xml.WriteEndDocument();
}

WebClient client = new WebClient();

client.UploadFile("http://test.com/test.aspx", ms);

Solution

  • EDIT: Edited in 2013 as it looks like it was entirely wrong back when I originally answered...

    Options:

    • Take the byte array from the MemoryStream and use UploadData

      client.UploadData("http://test.com/test.aspx", ms.ToArray());
      
    • Use OpenWrite instead, and write to the stream returned

      using (var stream = client.OpenWrite("http://test.com/test.aspx"))
      {
          using (XmlWriter xml = XmlWriter.Create(stream, settings))
          {
              ...
          }
      }
      
    • Write the data to a file and then use UploadFile

      using (XmlWriter xml = XmlWriter.Create("tmp.xml", settings))
      {
          ...
      }
      client.UploadFile("http://test.com/test.aspx", "tmp.xml");
      // Delete temporary file afterwards
      

    I'd personally go for one of the first two approaches, to avoid the temporary file.