2011-03-26 73 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

相關問題