XNA: Load all content files in a folder

After playing around with XNA for a little while, I quickly realised 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 parse all files within a folder into any content type. The method requires that the specified folder is relative to the Content.RootDirectory folder.

/// <summary>
/// Load all content within a certain folder. The function
/// returns a dictionary where the file name, without type
/// extension, is the key and the texture object is the value.
///
/// The contentFolder parameter has to be relative to the
/// game.Content.RootDirectory folder.
/// </summary>
/// <typeparam name="T">The content type.</typeparam>
/// <param name="contentManager">The content manager for which content is to be loaded.</param>
/// <param name="contentFolder">The game project root folder relative folder path.</param>
/// <returns>A list of loaded content objects.</returns>
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 :)

About these ads