XNA: serializing object to isolated storage

I have a class that defines my level. I have an XML file in my Content Project that stores the details of the level.

I can load the details of the XML file from the Content Project with LoadContent(). This creates an object with all the details from the XML file.

Now, I want to save that game level into isolated storage.

All the examples that I've seen, indicate that I need to use XMLWriter and XMLSerializer. Why is that? Can I not use the mechanism that the XNA framework uses to load from the Content Pipeline?


You don't need an XMLWriter or XMLSerializer, but you do need a serializer. Below is an example of a my Generic IsolatedStorage Utilty

public static void Save<T>(string fileName, T item)
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(fileStream, item);
        }
    }
}

public static T Load<T>(string fileName)
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(fileStream);
        }
    }
}

When YOU reference the XML as an XNA content it is compiled throught the ContentPipeline. So when you load the Content you do it through the ContentManager. This XML file referenced should NOT be in the ContentPipeline because then it cannot be modified. You should leave Static files referenced through the ContentPipline and leave all Dynamic files saved in IsolatedStorage. Once files are comiled they cannot be changed thats why it cant be saved to the ContentPipeline.

链接地址: http://www.djcxy.com/p/95516.html

上一篇: 如何在同一类的实例之间共享派生字段?

下一篇: XNA:将对象序列化到独立存储