保存XDocument问题

时间:2013-06-04 05:41:42

标签: silverlight-4.0 linq-to-xml

我正在加载我的文档:

WebClient client = new WebClient();
        client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
        client.OpenReadAsync(new Uri("Rolls.xml", UriKind.Relative));

然后阅读完成:

 XDocument doc = XDocument.Load(XmlReader.Create(e.Result));

       using (Stream stream = e.Result)
       {
           {
               foreach (var roll in _rollsToAddStudentTo)
               {
                   doc.Element("rolls").Add(new XElement("rollid", roll));
               }
               doc.Save(stream);
           }

       }

问题是当它到达保存时我得到了错误

  

“不支持指定的方法。”

非常感谢帮助。 干杯

谢谢Jehof,

那么,我如何将我的文档合并到该异步方法中?

foreach (var roll in _rollsToAddStudentTo)
               {
                   doc.Element("rolls").Add(new XElement("rollid", roll));
               }

               WebClient client = new WebClient();
               client.OpenWriteCompleted += new OpenWriteCompletedEventHandler(client_OpenWriteCompleted);
               client.OpenWriteAsync(new Uri("Rolls.xml", UriKind.Relative));

我已经通过将我的逻辑改为以下来解决了这个问题。

 using (IsolatedStorageFile isoStore =
           IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Create new file
                using (IsolatedStorageFileStream isoStream =
                    new IsolatedStorageFileStream("Rolls.xml",
                        FileMode.Create, isoStore))
                {
                    // Write to the Isolated Storage for the user.
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    // Create an XmlWriter.
                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("Rolls");

                        foreach (var roll in _rollsToAddStudentTo)
                        {
                            writer.WriteStartElement("roll");
                            writer.WriteAttributeString("rollid", roll);
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

您尝试保存XDocument的流是readonly。因为它是您作为参数传递给您在方法client_OpenReadCompleted中注册的方法OpenReadCompleted的流。

如果您想通过WebClient保存XDocument,则需要调用其中一个OpenWriteAsync - 方法。