Take the 2-minute tour ×

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.

share|improve this question
possible duplicate –  Estefany Velez Jul 17 '12 at 6:08
add comment

3 Answers

up vote 4 down vote accepted

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);
share|improve this answer
@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. –  CSharpLearner Jul 17 '12 at 5:55
Good catch, corrected. –  Eric J. Jul 17 '12 at 7:28
add comment

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))


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;
share|improve this answer
add comment

@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();
    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();    
share|improve this answer
Although this solution works, @Eric J's answer is better. –  CSharpLearner Jul 17 '12 at 11:11
add comment

Your Answer


