如何在序列化后检查文件是否存在 - C#?
How to check if file exists after serialization - C#?
我使用这个函数通过序列化将我的游戏状态保存到文件中:
public void SaveForX86 ()
{
UpdateGameState();
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(Application.persistentDataPath + Helper.GAME_DATA_FILE_NAME);
GameData data = new GameData();
data.experience = experience;
data.score = score;
data.winPercent = winPercent;
data.tasksSolved = tasksSolved;
data.correct = correct;
data.additions = additions;
data.subtractions = subtractions;
data.multiplications = multiplications;
data.divisions = divisions;
data.useAddition = useAddition;
data.useSubtraction = useSubtraction;
data.useMultiplication = useMultiplication;
data.useDivision = useDivision;
data.minRange = minRange;
data.maxRange = maxRange;
data.longestChain = longestChain;
data.useIncrementalRange = useIncrementalRange;
data.gameStateDirty = gameStateDirty;
data.longestTaskInSeconds = longestTaskInSeconds;
data.overallTimeInSeconds = overallTimeInSeconds;
data.operandsSign = operandsSign;
data.difficulty = difficulty;
bf.Serialize(fs, data);
fs.Close();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
我想检查文件是否已创建。在这种情况下我该怎么做?
使用File.Exists:
if (File.Exists(Application.persistentDataPath + Helper.GAME_DATA_FILE_NAME))
{
....
}
您不需要像序列化失败(例如由于 IO 错误)一样抛出异常。因此,如果 none 被抛出,您的文件应该已经创建。
我使用这个函数通过序列化将我的游戏状态保存到文件中:
public void SaveForX86 ()
{
UpdateGameState();
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(Application.persistentDataPath + Helper.GAME_DATA_FILE_NAME);
GameData data = new GameData();
data.experience = experience;
data.score = score;
data.winPercent = winPercent;
data.tasksSolved = tasksSolved;
data.correct = correct;
data.additions = additions;
data.subtractions = subtractions;
data.multiplications = multiplications;
data.divisions = divisions;
data.useAddition = useAddition;
data.useSubtraction = useSubtraction;
data.useMultiplication = useMultiplication;
data.useDivision = useDivision;
data.minRange = minRange;
data.maxRange = maxRange;
data.longestChain = longestChain;
data.useIncrementalRange = useIncrementalRange;
data.gameStateDirty = gameStateDirty;
data.longestTaskInSeconds = longestTaskInSeconds;
data.overallTimeInSeconds = overallTimeInSeconds;
data.operandsSign = operandsSign;
data.difficulty = difficulty;
bf.Serialize(fs, data);
fs.Close();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
我想检查文件是否已创建。在这种情况下我该怎么做?
使用File.Exists:
if (File.Exists(Application.persistentDataPath + Helper.GAME_DATA_FILE_NAME))
{
....
}
您不需要像序列化失败(例如由于 IO 错误)一样抛出异常。因此,如果 none 被抛出,您的文件应该已经创建。