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.
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();
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;
}
@LB 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.