是否可以为 C# Windows 应用程序提供某种内部存储?

Is it possible to have some kind of inside storage for C# Windows App?

我创建了一个小应用程序,可以在单击按钮时生成一个随机数,目前我将该数字保存在一个 .txt 文件中。

private void button1_Click(object sender, EventArgs e)
{
    Random rnd = new Random();
    int random = rnd.Next(1, 10000);
    // saving to a file is not an option!
    //File.AppendAllText(@"C:\Users\Public\no.txt", random + Environment.NewLine);
}

要解决的问题是这个随机生成的数字必须是唯一的(范围从1到9999)所以每次生成数字时我都会检查这个数字是否以前生成过。但要做到这一点,我必须记录每个生成的数字,以便能够检查、比较,如果存在则生成一个新数字,直到所有数字都被使用。

所以问题是:是否有可能以某种方式在应用程序中保留记录,这样我就不必创建任何额外的文件?

更新

关闭应用程序后,必须保存之前的号码才能创建唯一的新号码!

.NET 程序集没有 "inside storage"。保存文件有什么问题?

  1. 使用 Special Folder 而不是硬编码字符串

  2. 考虑使用 ProgramDataAppData

此外,如果您想轻松管理一个运行时对象,您可以使用Serialization

您也可以使用 registry 或数据库来保存您的数据。

我认为简单的答案是调整函数在您的应用程序上下文中的工作方式。

我会改变逻辑如下:

  • 程序为运行时,将列表保存在数组中
  • 当您需要添加新数字时,调整数组大小然后添加它
  • 退出时,将数组内容保存到文件中(以您选择的格式,我个人将其设为逗号分隔)
  • 开始时,加载文件并填充数组(如果用逗号或其他字符分隔,请将其读入字符串并使用拆分函数。)

调整数组大小的重要 code/pieces 是:

// should be in an accessible class scope - public or maybe even static
int[] myList = new list[0];             //start at 0 or empty

//function ressize Array by 1, accessible class scope - public or even static
static public int[] incrementIntArrayBy1(int[] oldArray){
        int[] newArray = new int[oldArray.Length + 1];
        Array.Copy(oldArray, newArray, oldArray.Length);
        return newArray;
    } 

//function on button
private void button1_Click(object sender, EventArgs e){
    mylist = incrementIntArrayBy1(myList);
    myList[myList.length-1] =  new Random().Next(1, 1000);
}
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
randoms = string.IsNullOrEmpty(ConfigurationManager.AppSettings["randoms"]) ? new List<int>() : ConfigurationManager.AppSettings["randoms"].Split(',').Select(int.Parse).ToList();
Random rnd = new Random();
int random = rnd.Next(1, 10000);
if (!randoms.Contains(random))
{
    randoms.Add(random);
    config.AppSettings.Settings.Add("randoms", string.Join(",", randoms.Select(p => p.ToString()).ToList()));
    config.Save(ConfigurationSaveMode.Minimal);
}

您可以在应用设置中定义密钥:

<configuration>
  <appSettings>
    <add key="randoms" value="" />
  </appSettings>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
 </startup>
</configuration>

我不确定 config.AppSettings.setting.Add 是如何工作的。我认为它通过连接为前一个增加了价值。

我生成的随机数会略有不同。

  1. 创建一对存储在一起的整数。
  2. 将 1 到 9999 的所有数字存储为对中的第一个数字
  3. 生成一个随机整数作为第二个数字(任意大小)
  4. 根据第二个数字对对排序
  5. 将这些对保存在一个文件中
  6. 如果您需要 1 到 9999 之间的整数,请阅读列表中的下一个数字
  7. 阅读完所有内容后,返回步骤 3。

这避免了必须检查所有数字以查看它们是否以前生成过,这可能会在您到达最后几个数字时造成延迟。