3
votes

I'm running into a lot of trouble while attempting to streamline XNA texture loading. I've given up on dynamically loading textures from a specified directory, so now I'm just trying to work with an organized collection of folders in the solution's content. I'm trying to use the following line of code:

Content.Load<Texture2D>(".\\Graphics\\Characters\\Char1");

"Char1" is the correct asset name, and it is stored in "Graphics\Characters" under Content in my solution explorer, but it still throws a "file not found" error. What am I doing wrong here?

EDIT: Turns out the debug bin folder created the wrong directory stucture: \Graphics\Characters\Characters. Thanks for the help regardless!

4
It is possible to get a file listing for a given directory (using System.IO.Path, for example) and using that file listing, stripping the .xnb extensions, to dynamically load an entire directory of assets.Andrew Russell

4 Answers

5
votes

Try removing your leading slash. eg,

Content.Load<Texture2D>("Graphics\\Characters\\Char1");

Are you using a content project for these assets? You can set the 'Content Root' directory and the assets are all in relative paths from there.

Have a look at this msdn entry, hopefully that might help you out. Good luck.

4
votes

From what you're saying, that the file is located in 'Content', make sure you do this before loading up anything:

Content.RootDirectory = "Content"

And get rid of the '.\' part.

2
votes

You can set the RootDirectory property in Content to the root location of your content files. This will make your paths work correctly.

Also, no need for the single dot .\

1
votes

What is your working directory? Typically it is bin\Debug (the location of the exe that is generated) and unless you are telling Visual Studio to copy your content files to this directory they are not located there.

Several options to fix this

  1. You can add your content files to Visual Studio and set them to Deploy mode of Copy
  2. You can manually copy them once
  3. You can check to see if the current directory contains a particular file and go up two levels if it does not
  4. You can use a constant to define the base directory and flex it depending on whether you are debugging or not.

Here is an example of 3

private string BaseDirectory = ".";
if (!Directory.Exists(".\Graphics"))
{
    BaseDirectory = @"..\..";
}
...
Content.Load<Texture2D>(BaseDirectory + @"\Graphics\Characters\Char1");

Here is an example of the 4, note that if you are running in release mode this won't work too smoothly.

#if DEBUG
    private const string BaseDirectory = @"..\..";
#else
    private const string BaseDirectory = @".";
#endif
...
Content.Load<Texture2D>(BaseDirectory + @"\Graphics\Characters\Char1");

Also note that a string that starts with @ does not allow \ escapes and is thus much easier to use to define directories.