-2

So i got this piece of code

namespace kortspel
{
    public partial class Form1 : Form

    {

        ArrayList kortlek = new ArrayList();
        Image c1 = new Bitmap("C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/c1.png");

And i don't want to add in 50pictures with a unique name such as Image c2 = blablabla.

Some people have said i need to create a loop, to add in these 50pictures, so is there a easier way instead of adding in 50 Images in the array?

Ayy lamo
  • 31
  • 5
  • Do they all reside in one directory; moreover, do they have predictable names (e.g. c1, c2, c3) or are the the only thing residing in a single directory? – Brad Christie Feb 20 '13 at 01:23
  • Possible dupe http://stackoverflow.com/questions/2953254/cgetting-all-image-files-in-folder – zs2020 Feb 20 '13 at 01:26
  • 1
    Where are you adding them to? Also, don't use an `ArrayList` unless you're using .NET 1.1. Use a `List` or whatever you're putting into the list. – John Saunders Feb 20 '13 at 01:28
  • Define Array List of type `Image`, then get all files from directory that are images and in the loop declare them as `Image` and add to ArrayList – Andrew Feb 20 '13 at 01:28

2 Answers2

1

You can use Directory.GetFiles(string path, string searchPattern) to get an array of all the files in a directory matching a given pattern. Then, just iterate over the files in a loop like this:

string path = "C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/";
string[] files = Directory.GetFiles(path, "*.png");
List<Bitmap> images = new List<Bitmap>();
foreach (var file in files)
{
    images.Add(new Bitmap(file);
}
Ergwun
  • 12,579
  • 7
  • 56
  • 83
  • If you're using .NET 4.0 or above, try [`Directory.EnumerateFiles`](http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles.aspx) instead. No need to read all the file names into memory at once. – John Saunders Feb 20 '13 at 01:38
  • You can also do this with linq, var files = Directory.GetFiles("path").Where(x => x.Contains("png")); – Pete Garafano Feb 20 '13 at 01:39
0

Yes, Linq is a good way.

string path = @"C:\Users\Public\Pictures\Sample Pictures";
string[] files = Directory.GetFiles(path, "*.jpg");
var result = from jpeg in files.AsEnumerable()
             select Image.FromFile(jpeg);
Tonix
  • 258
  • 1
  • 10