Search code examples
c#xnaloadxna-4.0texture2d

Load all Texture2Ds in a folder


How can I load all image assets in a particular folder in my XNA game? The textures are located in the content project like normal, but say instead of copying line after line for each new texture I add, the ability to load them all automatically.


Solution

  • Mainly there are two ways

    1st : Rename your images from 1 to N, so that you can load images in a for loop such as

    List<Texture2D> images = new List<Texture2D>();
    string folderPath = "MyImages/";
    for(int i= 0; i<Count; i++)
    {
       try
       {
            images.Add(Content.Load<Texture2D>(folderPath + i.ToString));
       }
       catch
       {
            break;
       }
    }
    

    the code above works for specific count, you may change for iteration to while(true) incrementing i, the catch blog will break if there is not any images more.

    or use this (put the static class in the namespace of your game-project, not under any sub-namespace folder) it would work. if you do not want to extend your Content than remove "this" from the function)

    public static class MyExtension
    {
            public static List<T> LoadListContent<T>(this ContentManager contentManager, string contentFolder)
            {
                DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory + "/" + contentFolder);
                if (!dir.Exists)
                    throw new DirectoryNotFoundException();
                List<T> result = new List<T>();
    
                FileInfo[] files = dir.GetFiles("*.*");
                foreach (FileInfo file in files)
                {
                    result.Add(contentManager.Load<T>(contentFolder + "/" + file.Name.Split('.')[0]));
                }
                return result;
            }
    }
    

    This code has a problem if your real path's length will be greater than 256, the function will not work. So be careful.