Reputation: 1
int d = 0;
foreach (string curFile in System.IO.Directory.GetFiles("Content/img/"))
{
tiles[d] = Content.Load<Texture2D>(curFile);
d++;
}
I have the above code, which is supposed to search through the directory, img
, and assign each file to the tiles[]
array. However, it seems to be searching for .xnb
files rather than .png
's that I have the images saved as. How can I fix this?
Upvotes: 0
Views: 98
Reputation: 5762
The content manager in Xna works with precompiled xnb files.
So you have to search for the xnb files, remove the extension adn make the path relative to the content manger root.
var tiles = new List<Texture2D>();
foreach (var imagePath in System.IO.Directory.GetFiles("Content/img/", ".xnb"))
{
var xnaPath = Path.Combine( "Content/img",
Path.GetFileNameWithoutExtension(imagePath));
tiles.Add( Content.Load<Texture2D>(xnaPath) );
}
if your content manager root folder is "content", then you shoould combine with the "img" folder, not the "content/img"
Upvotes: 1
Reputation: 137487
Directory.GetFiles(string path)
is going to return the full path of every file in that directory. Since you want only the .png files, you should use Directory.GetFiles(string path, string searchPattern)
which takes a second argument that specifies a search pattern.
Directory.GetFiles("Content/img/", ".png");
Also, since you're using an array for tiles
, I forsee your code having issues, as you probably don't know how many textures you're going to load from the directory. Instead, I suggest you use a List<T>
:
var tiles = new List<Texture2D>();
foreach (var imagePath in System.IO.Directory.GetFiles("Content/img/", ".png"))
{
tiles.Add( Content.Load<Texture2D>(imagePath) );
}
You could even get a little LINQ-crazy and do it in "one" line:
var tiles = Directory.GetFiles("Content/img/", ".png")
.Select( Content.Load<Texture2D> );
Upvotes: 3