序列化后如何检查文件是否存在 - C#?

时间:2016-02-26 12:28:51

标签: c# serialization unity3d filestream binaryformatter

我使用此功能将我的游戏状态保存到序列化文件中:

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);
    }
}

我想检查文件是否已创建。在这种情况下我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用File.Exists

if (File.Exists(Application.persistentDataPath + Helper.GAME_DATA_FILE_NAME))
{
  ....
}

答案 1 :(得分:1)

您不需要像序列化失败一样(例如,由于IO错误),应该抛出异常。因此,如果没有抛出您的文件应该已经创建。