Search code examples
c#winformsloadimage

Load first image with any name, solve exception error, copy dropped image to folder


I have a Form that loads its default BgImage from a subfolder at the location of my application.
When the default BackgroundImage is visible, it can be used as a drop area for other common bitmap formats(drag and drop image from Windows Explorer).
If there are any images in the subfolder, the image which is at the first position in the folder will be loaded as the default BackgroundImage.

string path = (full path to folder here, @"image_default\");
string[] anyfirstimage = Directory.GetFiles(path);

if (String.IsNullOrEmpty(anyfirstimage[0]))
{
    // do nothing
}
else
{
    this.BackgroundImage = Image.FromFile(anyfirstimage[0]);
}

How could I improve the above code, so that I don't get an exception 'Index bounds outside the array' when the subfolder contains no images?
Instead of getting an exception error in this case - is there a way for the next image drag and drop into that area to copy it into the subfolder automatically as the new default image, every time the Form runs and there are no images in the subfolder?


Solution

  • You can actually use Application.ExecutablePath to get the executable path. and then just easily check if the count of files in there are more than zero.

    string path=Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"image_default");
    string[] anyfirstimage = Directory.GetFiles(path, "*.jpg");
    if(anyfirstimage.Length > 0) BackgroundImage = Image.FromFile(anyfirstimage[0]);
    

    If there might be other files than images, make sure that you use the pattern overload of the GetFiles() like Directory.GetFiles(path, "*.jpg") to make sure that no other file format is selected.

    and as the answer for your comment, search pattern does not accept multiple patterns but you may filter them later like:

    var anyfirstimage = Directory.GetFiles(path).Where(x=> {var l = x.ToLower();
    return l.EndsWith(".jpg") || l.EndsWith(".png") || l.EndsWith(".gif");}).ToArray();
    

    finally, the code should be like this:

    string path=Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"image_default");
     string anyfirstimage = Directory.GetFiles(path).Where(x=> {var l = x.ToLower();
      return l.EndsWith(".jpg") || l.EndsWith(".png") || l.EndsWith(".gif");}).FirstOrDefault();
    if(anyfirstimage != null) BackgroundImage = Image.FromFile(anyfirstimage);