我試圖本地高分系統添加到我的比賽,有一個整型磚牆與文件讀寫運行,根據程序員和講師我知道在現實生活中和在互聯網上的一些教程我的代碼應該工作,因爲我想要它,但是無論何時我開始我的遊戲我的高分不加載,下面是我的閱讀和寫入文件的功能,是有我犯的錯誤嗎?我的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'爲空將拋出異常。你可以事先檢查一下流的長度,或者在打開它之前檢查文件是否存在(如果它不存在,退出函數) –