基本上,我正在编写在IsolatedStorage中创建新文件的代码,我确信我正确地关闭了流,但肯定有什么东西遗漏了,你能看看它,以确保我没有遗漏什么明显的东西吗?
下面是我的save函数,它是抛出错误的地方,一旦用户输入他/她的名字,就会在游戏结束时调用它:
public void SaveHighScores(string NewName, int NewScore)
{
SortHighScores(NewName, NewScore);
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("HighScores.txt", FileMode.CreateNew, isoStore))
{
using (StreamWriter writer = new StreamWriter(isoStream))
{
for (int i = 0; i < 5; i++)
{
writer.WriteLine(MyScores[i].Name);
writer.WriteLine(MyScores[i].Score);
}
writer.Close();
}
isoStream.Close();
}
}
catch (IsolatedStorageException e)
{
throw e; // "IsolatedStorageException was unhandled" error now occurs here
}
}这是我的Read函数,它在游戏开始时在初始化过程中被调用一次:
public void ReadHighScores()
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
if (isoStore.FileExists("HighScores.txt"))
{
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("HighScores.txt", FileMode.Open, isoStore))
{
using (StreamReader reader = new StreamReader(isoStream))
{
int i = 0;
while (!reader.EndOfStream)
{
MyScores[i].Name = reader.ReadLine();
string scoreString = reader.ReadLine();
MyScores[i].Score = Convert.ToInt32(scoreString);
i++;
}
reader.Close();
}
isoStream.Close();
}
}
catch (IsolatedStorageException e)
{
throw e;
}
}
else
{
if (!failedRead)
{
failedRead = true;
ReadHighScores();
}
}
}有谁能解释一下这件事吗?
编辑
好的,因为某些原因,当我第一次在新安装的应用程序上调用保存游戏功能时,它现在可以工作了,但是下一次我玩的时候,或者当我重新启动游戏并再次玩的时候,它在尝试保存时崩溃了,这很奇怪,FileMode.CreateNew可能是我出错的地方吗?
编辑
是的,当文件已经存在时,FileMode.CreateNew会抛出异常,所以我在创建新文件之前添加了isoStore.DeleteFile("HighScores.txt"),现在工作起来像做梦一样:)
已解决
发布于 2013-02-13 03:58:08
当文件已经存在时,FileMode.CreateNew会抛出异常,因此您必须在创建新文件之前调用isoStore.DeleteFile(string FileName),或者,如果您不是绝对需要使用FileMode.CreateNew,请使用FileMode.Create
https://stackoverflow.com/questions/14839211
复制相似问题