2011-03-26 98 views
1

我已经使用Visual Studio 2008成功创建了XML,但Visual Studio 2010中的Windows Phone 7应用程序似乎没有支持相同的语法。在Windows Phone 7应用程序中使用Visual Studio 2010创建Xml文件C#

我使用下面的命名空间:

using System.Xml.Linq; 
using System.Xml; 

我的代码是:

private const string filename = @"c:\sampledata.xml"; 


XmlWriterSettings settings = new XmlWriterSettings(); 
settings.Indent = true; 
settings.OmitXmlDeclaration = true; 
settings.NewLineOnAttributes = true; 
byte[] byteArray = Encoding.UTF8.GetBytes(filename); 
MemoryStream strm = new MemoryStream(byteArray); 
XmlWriter writer = XmlWriter.Create(strm, settings); 
writer.WriteStartDocument(true); 
writer.WriteComment("sample XML"); 
writer.WriteStartElement("root-node"); 
writer.WriteElementString("child-node", "The element value"); 
writer.WriteStartElement("next-child"); 
writer.WriteAttributeString("some-attribute", "A value"); 
writer.WriteAttributeString("another-attribute", "Another value"); 
writer.WriteValue("The next element value"); 
writer.WriteEndElement(); 
writer.WriteEndDocument(); 
writer.Close(); 

我收到以下错误:

Memory stream is not expandable

当我谷歌它,我找不到解决方案。我不知道我的方法是否正确。请指导我继续进一步......

回答

2

当您创建MemoryStream时,您使用了用字节数组进行初始化的ctor。这会创建一个不可调整大小的实例,其最大容量与初始化的容量一样大。

要么使用不同的构造函数创建MemoryStream,要么确保写入的内容不大于原始字节[]大小。

+0

如何确保写入文件大于原始字节大小 – Ash 2011-03-26 07:51:46

+0

在走得太远之前,我相信您正在为WP7编写代码,在这种情况下,您需要读取/写入独立存储。按照这个问题中最后一个答案中的例子:[link](http://stackoverflow.com/questions/4083169/add-elements-to-xml-file-in-wp7) – Gambit 2011-03-27 00:55:07

相关问题