I have created a program that generates a random image from a folder of all the world's flags. First, it generates an image as it loads, then it can keep randomizing the shown image if the user clicks on a button. Currently, I have created a method called "ImageGenerator" and call that method both in Form1() and my button click method (view code: https://pastebin.com/qzWXqP0P).
public partial class Form1 : Form
{
public void ImageGenerator()
{
string[] flagImageSources = new string[196];
StreamReader flagImageSourceReader = File.OpenText("flagImageSourceFile.csv");
for (int i = 0; i < flagImageSources.Length; i++)
{
string s = flagImageSourceReader.ReadLine();
flagImageSources[i] = s;
}
Random numberGenerator = new Random();
int imageNumber = numberGenerator.Next(0, 196);
string flagImageSrc = flagImageSources[imageNumber];
flagPictureBox.ImageLocation = @flagImageSrc;
}
public Form1()
{
InitializeComponent();
ImageGenerator();
}
private void submitBtn_Click(object sender, EventArgs e)
{
ImageGenerator();
}
}
To me it feels like the linked code is rather inefficient as it recreates the array flagImageSources (which contains the paths to each flag image) every time a new image is to be generated in the picture box. How can I run the code on lines 6 through 13 only once, and then just run the code on lines 16 through 21 when randomizing images?