如何将变量保存到一个新的文本文件中,以便下次程序运行时加载这些变量



new c#。我正在制作一款基于主机的RPG。游戏进展得很顺利,但我需要知道如何拯救游戏。我想,有一种方法来保存变量从我的应用程序到一个文本文件,可用于加载变量时,应用程序再次运行。不幸的是,我不知道从哪里开始。

我还需要一种方法去一个点在代码加载保存文件时。

我的一些变量包括:

int xCoordinate, yCoordinate, hp, hpmax, level;

将一些变量写入文本文件很简单:

TextWriter tw = new StreamWriter("SavedGame.txt");
// write lines of text to the file
tw.WriteLine(xCoordinate);
tw.WriteLine(yCoordinate);
// close the stream     
tw.Close();

然后把它们读回来:

// create reader & open file
TextReader tr = new StreamReader("SavedGame.txt");
// read lines of text
string xCoordString = tr.ReadLine();
string yCoordString = tr.ReadLine();
//Convert the strings to int
xCoordinate = Convert.ToInt32(xCoordString);
yCoordinate = Convert.ToInt32(yCoordString);
// close the stream
tr.Close();

您可以使用二进制序列化相当容易地完成此任务。首先,创建一个包含您想要编写的所有变量的类:

[Serializable]
class Data
{
    int x;
    int y;
}

然后按如下方式使用:

Data data = new Data();
//Set variables inside data here...
// Save data
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = File.OpenWrite("C:\Temp\bin.bin"))
{
    formatter.Serialize(stream, data);
}

您可以将变量保存到XML文件中,并在下次启动时加载它们,这个过程称为序列化。请参阅这里的帮助器类,它可以将大多数c#对象(包括列表,但不包括字典)序列化和反序列化到XML文件。

如果您只希望将几个值传输到下一个控制台应用程序,则可以使用命令行参数或管道。

我的脚本保存变量(隐藏,加密,可以编辑,更改,保存,删除)

public class SavingPlugin
{
    public static void SaveVariable(string savename, TypeCode tc, object value,string Encryption_password)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + @"" + savename + "." + tc.ToString();
        if (!File.Exists(path))
        {
            var myfile = File.Create(path);
            myfile.Close();
            string val = value.ToString();
            string encrypted = StringCipher.Encrypt(val, Encryption_password);
            File.WriteAllText(path, encrypted);
            File.SetAttributes(path, FileAttributes.Hidden);
        }
        else
        {
            string txt = "";
            try
            {
                txt = StringCipher.Decrypt(File.ReadAllText(path), Encryption_password);
                File.SetAttributes(path, FileAttributes.Normal);
                string val = value.ToString();
                string encrypted = StringCipher.Encrypt(val, Encryption_password);
                File.WriteAllText(path, encrypted);
                File.WriteAllText(path, encrypted);
                File.SetAttributes(path, FileAttributes.Hidden);
            }
            catch
            {
                MessageBox.Show("Incorrect password : " + Encryption_password + " for the variable : " + savename + "." + tc.ToString());
            }
        }
    }
    public static object GetVariable(string savename, TypeCode tc, string Encryption_password)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + @"" + savename + "." + tc.ToString();
        File.SetAttributes(path, FileAttributes.Normal);
        string txt = "";
        try
        {
            txt = StringCipher.Decrypt(File.ReadAllText(path), Encryption_password);
            File.SetAttributes(path, FileAttributes.Hidden);
            var value = Convert.ChangeType(txt, tc);
            return value;
        }
        catch
        {
            MessageBox.Show("Incorrect password : " + Encryption_password + " for the variable : " + savename + "." + tc.ToString());
            return null;
        }

    }
    public static void DeleteVariable(string savename,TypeCode tc)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + @"" + savename + "." + tc.ToString();
        File.SetAttributes(path,FileAttributes.Normal);
        File.Delete(path);
    }
    public static bool Exists(string savename,TypeCode tc)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + @"" + savename + "." + tc.ToString();
        bool _true = true;
        try
        {
            File.SetAttributes(path, FileAttributes.Normal);
            File.SetAttributes(path, FileAttributes.Hidden);
        }
        catch
        {
            _true = false;
        }
        return _true;
    }
}
public static class StringCipher
{
    // This constant is used to determine the keysize of the encryption algorithm in bits.
    // We divide this by 8 within the code below to get the equivalent number of bytes.
    private const int Keysize = 256;
    // This constant determines the number of iterations for the password bytes generation function.
    private const int DerivationIterations = 1000;
    public static string Encrypt(string plainText, string passPhrase)
    {
        // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
        // so that the same Salt and IV values can be used when decrypting.  
        var saltStringBytes = Generate256BitsOfRandomEntropy();
        var ivStringBytes = Generate256BitsOfRandomEntropy();
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                            var cipherTextBytes = saltStringBytes;
                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Convert.ToBase64String(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }
    public static string Decrypt(string cipherText, string passPhrase)
    {
        // Get the complete stream of bytes that represent:
        // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
        // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
        // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }
    private static byte[] Generate256BitsOfRandomEntropy()
    {
        var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            // Fill the array with cryptographically secure random bytes.
            rngCsp.GetBytes(randomBytes);
        }
        return randomBytes;
    }
}

如何使用:

SavingPlugin.SaveVariable("int16",TypeCode.Int16,15,"awwdad");
MessageBox.Show(SavingPlugin.GetVariable("int16", TypeCode.Int16,"awwdad").ToString());

您可以使用savvariable更改已经存在的变量的值,但是您需要输入正确的密码

最新更新