Open a local xml file in WP7

情到浓时终转凉″ 提交于 2019-12-11 13:26:49

问题


Me having a local xml file and need to load it to Isolated Storage when my app. starts for first time. but if i am opening that file using stream OR File.Open it's throwing an error. Also i need to store that file in serialized form. Please help, as being new to WP7 and C# not able to crack it.

Following code is used for opening the XML file:

FileStream stream = new FileStream("site.xml", FileMode.Open);

回答1:


If the file is a part of your project then you can add the file to your project as resource. That means file "Build Action" of the file should be "Resource". And the following function can read the file from project resource.

Stream stream = this.GetType().Assembly.GetManifestResourceStream("Namespace.FileName.FileExtentation");

Now you can read the stream according to the file type. If it is a XML file then you can read it like below.

As an example

XElement element = XElement.Load(stream);
foreach (XElement phraseElement in element.Elements())
{
    MyClass foo = new foo();
    foreach (XAttribute attribute in phraseElement.Attributes())
      foo.Text = attribute.Value;

}

How to write to isolated storage and read a file from isolated storage? Please check out the following link

http://www.codebadger.com/blog/post/2010/09/03/Using-Isolated-Storage-on-Windows-Phone-7.aspx

Also you can checkout the link below regarding Local Data Storage for Windows Phone.

http://msdn.microsoft.com/en-us/library/ff626522%28v=vs.92%29.aspx




回答2:


You need to specify the FileAccess mode as well for any Content type resource, since you can't open it in write-mode.

Try change your code to:

FileStream stream = new FileStream("site.xml", FileMode.Open, FileAccess.Read);

Also, see this question: How to fix exception MethodAccessException during file reading?



来源:https://stackoverflow.com/questions/7252435/open-a-local-xml-file-in-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!