【问题标题】:Is there a variable that doesn't reset each time an application is launched? [closed]是否存在每次启动应用程序时都不会重置的变量? [关闭]
【发布时间】:2020-11-04 06:39:28
【问题描述】:

让我解释一下:

假设我有一个Boolean 变量,在我编写程序代码时,我将它设置为False。 现在,每次我构建/运行应用程序时,这个 Boolean 变量都会重新设置为 False

我希望如果用户输入一个特定的字符串,Boolean 将更改为True,然后每次我重新运行应用程序时,它都会保留True 的值,换句话说,变量现在将重置为True

【问题讨论】:

  • 这将是一个文件、数据库或注册表项。
  • 您想永久保存数据吗? this answer 可能是第一步
  • 您可以根据需要对持久化数据进行加密,但它应该仍然很容易破解。我猜您正在尝试实施串行密钥/复制保护方案?基本上,如果像 Microsoft 或 Adob​​e 这样的公司无法阻止其产品的盗版,我认为您无需为此付出太多努力。

标签: c# forms variables


【解决方案1】:

你可以保存布尔值。

你是这样做的:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class SaveSystem
{

// =====Saving=====

// "path" should be filled with the full path of the save directory, including the file name and the file extension.
    public static void Save(bool boolean, string path)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream = new FileStream(path, FileMode.Create);

        formatter.Serialize(stream, boolean);
        Debug.Log($"Bool saved at {path}");
        stream.Close();
    }


// =====Loading=====

// "path" should be filled with the full path of the save directory, including the file name and the file extension.
    public static bool LoadOptions(string path)
    {
        if(!File.Exists(path))
        {
            Console.WriteLine($"Options file not found in {path}"); //For debugging, is removable
            return false;
        }
        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream = new FileStream(path, FileMode.Open);
        bool stuff = formatter.Deserialize(stream) as bool;
        Debug.Log($"Bool loaded at {path}");
        stream.Close();
        return stuff;
    }
}

只需确保在启动时加载它。 这种保存方法也适用于任何其他事物,例如 int 和您自己的类(,前提是它在顶部 上有“[System.Serializable]”,并且您可以修改它保存/加载的数据类型。 )

[编辑] 这是许多保存算法之一。这是一种保存到二进制文件的方法。如果您想保存到文本文件,其他答案可能会有所帮助。请记住,二进制文件比 text/xml 文件更难篡改,因此这是推荐的保存方式。

【讨论】:

  • 有没有办法让外部用户无法阅读?我不想让用户能够读取/写入/更改文件内容以及布尔值
  • 从技术上讲,没有。但是,如果你想让它很难做到,这就是方法。保存到文本文件通常很糟糕,因为用户可以轻松地使用记事本修改一些值。如果您保存到二进制文件,则情况并非如此。
  • 我想像您使用的那样使用BinaryWriter,但是在创建文件后,我打开的是使用记事本,不幸的是我可以用纯文本阅读它。如您所知,我希望它不容易阅读。这是我使用的代码:using (BinaryWriter writer = new BinaryWriter(File.Open("Binary.bin", FileMode.Create))) { writer.Write("string text\n"); }
  • @Twins96:您可以轻松地在运行应用程序之前创建文件的副本,然后再替换它。或者也许只是删除它。或者在虚拟机中运行所有内容,每次运行后恢复为快照。没有办法阻止用户破解您在本地存储值的方案。您可以通过每次使用身份验证服务器来提高几率,但是 1) 如果您的客户需要互联网才能运行应用程序,他们可能会生气,并且 2) 一个坚定的黑客无论如何都会破解可执行文件。
  • 我使用的是 BinaryFormatter,而不是 BinaryWriter
最近更新 更多