It makes absolutely no sense to load all those images in memory at once. Keep the images in the directory and create a container which holds only the image names. Better yet, rename all files to have the same names as some integer index, better in hexadecimal form. Then you can have the class with the indexed access to images. Don't forget to forget image references when an image is no longer displayed. This is needed to make the reference unreachable, so the GAC could eventually destroy them. Also, you would need to
Dispose()
each image when it is no longer needed.
It could look something like:
using System.Drawing;
class ImageCollection {
internal Image[] array =
Image this[int index] {
get {
Image image = array[index];
if (image != null) return image;
string imageFileName = string.Format("{0:X8}", index);
image = Image.FromFile(imageFileName);
array[index] = image;
return image;
}
}
internal void Forget(int index) {
Image image = array[index];
if (image == null) return;
image.Dispose();
array[index] = null;
}
}
Here, you just assume that
Directory.GetFiles
give you the count of files with file names in one directory with the names based on hexadecimal numbers 00000000, 00000001,… 0000000A, etc. Initially, you create the array with
Count
of null values. Each time you need a file at some index, and find that the image is not presently in the list (it's null), you calculate the file name and load it to the array element, and later use it. You can forget some elements when they are no longer displayed. This is important: you cannot keep them all loaded at the same time.
—SA