Search code examples
c#c#-4.0xnaxna-4.0

XNA Content Directory Iteration


Are there any objects or functions that can iterate through the files in a set directory in XNA Content?

I have a set of images in a directory in my game's content, but as the project goes on, I will be adding more. However, I don't want to have to go and add a line of code every time I add a new image, it would be much better if I was able to just iterate through every file in the directory and load them into an array. Is there any way to do this?


Solution

  • You can use this handy extension method

    public static class Extension Methods
    {
            public static List<T> LoadContentFolder<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;
            }
    }
    

    Remove the "this" keyword from the constuctor if you dont want to extend the class. You can use it like so:

    Dictionary<string,Texture2D> folderContent = Content.LoadContentFolder<Texture2D>("FolderName");
    

    FolderName is just a subfolder within your content folder

    And access by doing folderContent["MyAssetName"]