2017-05-02 16 views
0

存在於我的老項目時,我保存的XDocument,保存功能有一個像7個重載包括使用網絡的核心是「字符串文件名」在我的新項目的XDocument保存字符串參數不net.core

現在沒有超載接受文檔應該保存的字符串。

我有這樣的:

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

我如何保存的XDocument在我的硬盤?

謝謝。

回答

0

好吧,我發現如何做到這一點與現有方法。

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(); 
+0

不要忘記使用'使用(FileStream fileStream = .. 。){...}' –

2

您可以像這樣保存XDocument,但您需要添加一些SaveOptionsimplementation)。看一看在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); 
    } 
} 

您可以使用一個作家實現自己的解決方案,或直接致電像

file.Save(@"C:\1\email.xml", SaveOptions.None); 
+0

我不能這樣做:file.Save(@「C:\ 1 \ email.xml」,SaveOptions.None);什麼版本的NetCore是那個? –

+0

.NET Core 2.0包含顯示的System.Linq版本4.2.0.0 – Fruchtzwerg

+0

我正在使用1.1 :( –