将类数据另存为文本文件

问题描述 投票:1回答:2

我正在使用binaryFormatter加密数据,但我想不加密就保存它。所以下次我只是放下它。这是我正在使用的代码。

   //Creat a binaryFormatter
    BinaryFormatter formatter = new BinaryFormatter();

    //Direction, Filename and Extention
    string path = Application.persistentDataPath + "/enem.sav";

    //Creat the File (Blank)
    FileStream stream = new FileStream(path, FileMode.Create);

    //Get the Data
    EnemData data = new EnemData();

    //Enter the Data and Encrypt it
    formatter.Serialize(stream, data);
    stream.Close();
c# visual-studio unity3d io
2个回答
2
投票

您可以使用JsonUtility.ToJson将对象的数据转换为JSON格式。

public class PlayerState : MonoBehaviour
{
    public string playerName;
    public int lives;
    public float health;

    public string SaveToString()
    {
        return JsonUtility.ToJson(this);
    }

    // Given:
    // playerName = "Dr Charles"
    // lives = 3
    // health = 0.8f
    // SaveToString returns:
    // {"playerName":"Dr Charles","lives":3,"health":0.8}
}

Here,您可以找到如何在文件中读取和写入字符串。

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);

要加载数据,只需使用JsonUtility.FromJsonJsonUtility.FromJsonOverwrite

示例:

public class PlayerState : MonoBehaviour
{
    public string playerName;
    public int lives;
    public float health;
    public string path = "your file path";

    public string SaveToString()
    {
        File.WriteAllText(path, JsonUtility.ToJson(this));
    }

    public static PlayerState Load(string path)
    {
        return JsonUtility.FromJson<PlayerState>(File.ReadAllText(path));
    }
}

0
投票

不确定您的需求。如果您只想序列化(将您的类转换为二进制表示形式并保存到文件中),然后将其取回,则该方法适用于您:

    //Create a binaryFormatter
    BinaryFormatter formatter = new BinaryFormatter();

    //Direction, Filename and Extention
    string path = Application.persistentDataPath + "/enem.sav";

    //Creat the File (Blank)
    Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);

    //Get the Data
    EnemData data = new EnemData { Id = 123, SomeBool = true, Name = "Enem" };

    //Enter the Data and Encrypt it
    formatter.Serialize(stream, data);
    stream.Close();


    //Restore it

    Stream stream2 = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    EnemData restoredClass = (EnemData)formatter.Deserialize(stream2);
    stream.Close();

但是请记住,您必须将您的课程标记为可序列化:

[Serializable]
public class EnemData
{
    public int Id { get; set; }
    public bool SomeBool { get; set; }
    public string Name { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.