Reputation: 2498
In my old projects when I save a XDocument, the Save function has like 7 overloads including a "string fileName"
Now in my new project using Net Core there's no overload accepting a string where the document should be saved.
I have this:
XDocument file = new XDocument();
XElement email = new XElement("Email");
XElement recipientsXml = new XElement("Recipients");
foreach (var r in recipients)
{
var rec = new XElement("Recipient",
new XAttribute("To", r));
recipientsXml.Add(rec);
}
email.Add(recipientsXml);
file.Add(email);
file.Save(@"C:\1\email.xml");
How I save the XDocument in my disk?
Thanks.
Upvotes: 0
Views: 504
Reputation: 2498
Ok I found how to do that.
FileStream fileStream = new FileStream(@"C:\1\emails.xml");
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
XmlWriter writer = XmlWriter.Create(fileStream, settings);
XDocument file = new XDocument();
XElement email = new XElement("Email");
XElement recipientsXml = new XElement("Recipients");
foreach (var r in recipients)
{
var rec = new XElement("Recipient",
new XAttribute("To", r));
recipientsXml.Add(rec);
}
email.Add(recipientsXml);
file.Add(email);
file.Save(writer);
writer.Flush();
fileStream.Flush();
Upvotes: 0
Reputation: 11389
You can save the XDocument
like this, but you need to add some SaveOptions
(implementation). Have a look at the Implementation of XDocument:
public void Save(string fileName, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(fileName, ws))
{
Save(w);
}
}
You can implement your own solution using a writer, or simply call the existing method like
file.Save(@"C:\1\email.xml", SaveOptions.None);
Upvotes: 2