First, there's a mistake in the reading part: you're opening the file with FileMode.Create
.
And according to the documentation:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
So basically, your ReadHighScore
is deleting the old file and creating a new one. Which is, I believe, not what you wanted to do. Replace FileMode.Create
by FileMode.OpenOrCreate
(only in the ReadHighScore
method) and you should have a better result.
Also, there's an error in the SaveHighScore
, on this line:
stream.Write(myByteArray, 0, streamLength);
Since you're creating the file, streamLength
is supposed to be equal to 0. Therefore, you aren't writing anything. What you really want to do is:
stream.Write(myByteArray, 0, myByteArray.Length);
You should consider using StreamReader
, StreamWriter
, BinaryReader
, and BinaryWriter
to read/write into streams, as they are far easier to use.
Last but not least, the data you're reading and writing is wrong. In the SaveHighScore
method, you're trying to save an empty array, the actual high score is nowhere to be found. In the ReadHighScore
method, it's even worse: you're reading myByteArray.ToString()
, which will always be equal to System.Byte[]
.
In the end, your code should be something like: (given that highScore.score
is declared as int
)
public void ReadHighScore()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream("highscore.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, store))
{
using (var reader = new BinaryReader(stream))
{
highScore.score = reader.ReadInt32();
}
}
}
}
public void SaveHighScore()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream("highscore.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, store))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(highScore.score);
}
}
}
}