1

I want to transfer XML from client to some server using FTP. What I get is the XmlElement object. I know that I can create the File and upload it to appropriate location (FTP).

However, I think it's better to create File in memory (to avoid file saving on the local disk).

Can someone guide me how can i achieve this?

I am using C# 4.0.

Learner
  • 4,661
  • 9
  • 56
  • 102

3 Answers3

5

You can use FtpWebRequest.GetRequestStream() to write directly to the request stream without first saving the file on disk

Retrieves the stream used to upload data to an FTP server.

XmlElement.OuterXml returns a String representation of the XmlElement.

string xml = myXmlElement.OuterXml;
byte[] bytes = Encoding.UTF8.GetBytes(xml);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • @Erirc J. : FtpWebRequest.Write() method's first argument is of type `byte[]`. It's not of the string type which `OuterXml` property of the `XmlElement` returns. So your code will not work. – Learner Jul 17 '12 at 05:55
2

Ling2Xml is easier to use:

stream = ftpRequest.GetRequestStream();

XElement xDoc = new XElement("Root",
                    new XElement("Item1", "some text"),
                    new XElement("Item2", new XAttribute("id", 666))
                    );

xDoc.Save(stream);

or you can use serialization

XmlSerializer ser = new XmlSerializer(typeof(SomeItem));
ser.Serialize(stream, new SomeItem());

public class SomeItem
{
    public string Name;
    public int ID;
}
L.B
  • 114,136
  • 19
  • 178
  • 224
2

@L.B. gave the hint to use XDocument and it solved my problem.

Here is the solution:

  • Write a code to create XDocument object out of the XmlElement object.

    StringBuilder stringBuilder = new StringBuilder();
    XmlWriter xmlWriter = new XmlTextWriter(new StringWriter(stringBuilder));
    xmlElement.WriteTo(xmlWriter);
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(new StringReader(stringBuilder.ToString()));
    XDocument doc = XDocument.Load(xmlDocument.CreateNavigator().ReadSubtree(), LoadOptions.PreserveWhitespace);
    
  • Then use the FTP's stream like this.

    Stream ftpstream = ((FtpWebRequest)WebRequest.Create(path)).GetRequestStream();    
     doc.Save(ftpstream);
    
    ftpstream.Close();
    
Learner
  • 4,661
  • 9
  • 56
  • 102