我在XNA上玩游戏。
我目前正在向windows和xbox360写作。
这是解决以下问题的正确方法吗?
我想将文件保存到xbox上的隔离存储中,该存储已存在于我的内容中。 我有一个包含所有设置的settings.xml文件。在我的内容中,属性不被编译(标记为内容),如果更新则复制,因此可以修改,但仍在内容中维护。
我有一个保存和加载功能,对Windows和& xbox,目前正在加载GameSettings对象,但也可以保存和加载XML文件 负载:
public static GameSettings Load(string settingsFilename)
{
GameSettings settings; // Creates a new instance of GameSettings
#if WINDOWS
using (Stream stream = File.OpenRead(settingsFilename))// Open and Read-stream from the filename entered
{
XmlSerializer serializer = new XmlSerializer(typeof(GameSettings)); // Serializer of type GameSettings
settings = (GameSettings)serializer.Deserialize(stream); //Deserialize the xml file stream and fill the data into a GameSettings object
}
#elif XBOX
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(settingsFilename, FileMode.Open, FileAccess.Read, isf))
{
XmlSerializer serializer = new XmlSerializer(typeof(GameSettings));
settings = (GameSettings)serializer.Deserialize(stream);
}
}
#endif
return settings;
}
保存:
public static void Save(string settingsFileName, GameSettings settings)
{
#if WINDOWS
using (Stream stream = File.OpenWrite(settingsFileName))// Open and Write-stream from the filname entered
{
XmlSerializer serializer = new XmlSerializer(typeof(GameSettings)); // Serializer of type GameSettings
serializer.Serialize(stream, settings); // serialize the GameSettings data into the stream
}
#elif XBOX
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(settingsFileName, FileMode.OpenOrCreate, isf))
{
XmlSerializer serializer = new XmlSerializer(typeof(GameSettings));
serializer.Serialize(stream, settings);
}
}
#endif
}
在处理默认文件(如设置)时,是否还有其他方法不那么复杂或简单明了,只应在游戏第一次启动时创建,然后才能在运行时修改它。
答案 0 :(得分:1)
我使用以下方法将文件从内容保存到独立存储中: 代码非常简单,所以我不会发表评论。
public static void InitializeFiles()
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.FileExists("settings.xml"))
{
isf.CreateFile("settings.xml").Dispose();
XDocument xml;
using (Stream stream = File.Open("Content/settings.xml", FileMode.Open, FileAccess.Read))
{
xml = XDocument.Load(stream);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("settings.xml", FileMode.Create, isf))
{
xml.Save(stream);
}
}
}
}
但我仍然不确定这是否是一个好方法,因为它感觉很笨拙。所以我不会标记这个问题。