Load all content files in a folder in XNA

After playing around with XNA for a little while, I quickly realized how tedious it is to load all content manually, especially if the project uses a lot of images, sounds, textures etc.

The method below is an extension method that can load all files within a folder into any content type. The method requires that the specified folder is relative to the Content.RootDirectory folder.

public static Dictionary<String, T> LoadContent<T>(this ContentManager contentManager, string contentFolder)
   //Load directory info, abort if none
   DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory + "\\" + contentFolder);
   if (!dir.Exists)
      throw new DirectoryNotFoundException();
   //Init the resulting list
   Dictionary<String, T> result = new Dictionary<String, T>();

   //Load all files that matches the file filter
   FileInfo[] files = dir.GetFiles("*.*");
   foreach (FileInfo file in files)
      string key = Path.GetFileNameWithoutExtension(file.Name);

      result[key] = contentManager.Load<T>(contentManager.RootDirectory + "/" + contentFolder + "/" + key);
   //Return the result
   return result;

The function extends the ContentManager class, and can, for instance, be used by the main Game class like this:

  • var textures = Content.LoadContent<Texture2D>("Textures");
  • var models = Content.LoadContent<Model>("Models");
  • var songs = Content.LoadContent<Song>("Songs");
  • ...

The method returns  a dictionary, so if you want to access the “warrior” model in the models dictionary, you just have to access it as such:

  • var warriorModel = models["warrior"];

I am having some problems with pasting in code fragments into this blog, so if anyone can give me some tips for good plugins that can be used at wordpress.com, feel free to do so :)