我试图本地高分系统添加到我的比赛,有一个整型砖墙与文件读写运行,根据程序员和讲师我知道在现实生活中和在互联网上的一些教程我的代码应该工作,因为我想要它,但是无论何时我开始我的游戏我的高分不加载,下面是我的阅读和写入文件的功能,是有我犯的错误吗?我的WP7游戏要么不读或从IsolatedFileStream书写正确
public void ReadHighScore()
{
byte[] myByteArray = new byte[64]; // Creates a new local byte array with a length of 64
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) // Creates an IsolatedStorageFile within the User Storage
using (var stream = new IsolatedStorageFileStream("highscore.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, store)) // Creates a new filestream attatched to the storage file
{
if (stream != null) // Checks to see if the filestream sucessfully read the file
{
int streamLength = (int)stream.Length; // Gets the length of the filestream
stream.Read(myByteArray, 0, streamLength); // Parses the filestream to the byte array
}
else
myState = (int)game_state.Terminate; // Temporary Error checking, the function gets though this without triggering the 'terminate' gamestate
}
string ScoreString = myByteArray.ToString(); // Parses the byte array to a string
Int32.TryParse(ScoreString, out highScore.score); // Parses the string to an integer
}
public void SaveHighScore()
{
byte[] myByteArray = new byte[64]; // Creates a new local byte array with a length of 64
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) // Creates an IsolatedStorageFile within the User Storage
using (var stream = new IsolatedStorageFileStream("highscore.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, store)) // Creates a new filestream attatched to the storage file
{
if (stream != null) // Checks to see if the filestream sucessfully read the file
{
int streamLength = (int)stream.Length; // Gets the length of the filestream
stream.Write(myByteArray, 0, streamLength); // Parses the byte array to the filestream
}
else
myState = (int)game_state.Terminate; // Temporary Error checking, the function gets though this without triggering the 'terminate' gamestate
}
}
}
哇哦,谢谢!而且你已经告诉我,即使我能做的事情总是可以做得更干净,我仍然有很多要学习:) – TotalJargon
代码仍然需要一点工作,错过了一个EndOfStreamException,所以我想我'现在必须学会如何去做:P感谢您的帮助! – TotalJargon
@TotalJargon的确我错过了那一个。第一次调用'ReadHighScore'时,该文件将为'BinaryReader'为空将抛出异常。你可以事先检查一下流的长度,或者在打开它之前检查文件是否存在(如果它不存在,退出函数) –