简体   繁体   中英

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

I have created a small app to generate a random number on a button click and at the moment I am saving that number in a .txt file.

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

The problem to solve is that this random generated number must be unique (range from 1 to 9999) so every time when the number is generated I would check if that number was generated previously. But to do that I must keep a record of every generated number to be able to check, compare and if exists generate a new one until all numbers are used.

So the question is: Is it possible somehow to keep a record inside app so that I don't have to create any additional files?

update

After closing the app, previously numbers must be saved to be able to create unique new numbers!

There is no "inside storage" for an .NET assembly. What wrong with saving a file?

  1. use Special Folder instead of a hardcoded String

  2. Consider using ProgramData or AppData

Also if you want to manage an Runtime object easly, you could make use of Serialization .

You could also use the registry , or a database to save your data.

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

You can define the key in app setting:

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

I am not sure how config.AppSettings.setting.Add works. I think it adds value to the previous one by concatenating.

I think the simple answer is to adjust the way the function works in the context of your application.

I would change the logic as follows:

  • When the program is running, keep the list in an array.
  • When you need to add a new number, resize the array then add it
  • When you exit, save the array content to the file (in format of your choosing, personally I would make it comma delimited)
  • When you start, load the file and populate the array (if you delimited with a comma or other character(s), read it into a string and use the split function.)

The salient code/pieces to resizing the array are:

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

I would generate the random numbers slightly differently.

  1. Create a pair of integers stored together.
  2. Store all of the numbers 1 to 9999 as the first number in the pair
  3. Generate a random integer as the second number (any size)
  4. Sort the pairs on the second number
  5. Save these pairs in a file
  6. When you want an integer between 1 and 9999, read the next number on the list
  7. When you've read them all, go back to step 3.

This prevents having to check all the numbers to see whether they have been previously generated which may cause delays when you are reaching the last few numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM