The way you're creating the URI is correct. The trouble is that you're trying to use what is likely meant to be readable text (the name of a room) in a URI and as a flle name. You didn't specify what nameOfRoom
is, so I can't tell exactly why it's invalid.
There are ways around it. You could look at this answer which explains how to remove invalid characters from a file name.
But the best solution is not to have the problem. Don't use the name of the room as a file name. Your question indicates that a room has an ID, which is apparently an integer. Using that instead would be much easier:
using (var db = new DungeonContext())
{
room = db.Rooms.Where(b => b.RoomId == nrand);
}
and then
roomScreen.Source = new BitmapImage( new Uri($"/images/Room{room.RoomId}.png"));
If you want to use your code as-is, that's possible. When you do this:
nameOfRoom = db.Rooms.Where(b => b.RoomId == nrand).ToString();
you're calling ToString()
on what is presumably a Room
class. Unless you override that method, the result will always be the name of the class. (So it would be the same for every room.)
If you overrode the ToString
method:
public override string ToString()
{
return $"Room{RoomId}";
}
then calling room.ToString() would return "Room1" or "Room2", etc.
String interpolation calls ToString()
, so in that case you could just do
roomScreen.Source = new BitmapImage( new Uri($"/images/{room}.png"));
That works. One downside is that it's not explicit. Someone reading that line of code might not know that Room.ToString()
is also the value used to create a file name. You might also want to use the ToString()
method differently.
If you wanted to be really explicit and clear, you could create an extension method like this:
public static class RoomFileNameExtensions
{
public static string GetImageFileName(this Room room)
{
return $"Room{room.RoomId}.png";
}
}
Now the Room
class isn't responsible for knowing how file names are created. You could do this:
roomScreen.Source = new BitmapImage( new Uri($"/images/{room.GetImageFileName()}"));
You can use that both when creating the file and when reading the file. It ensures that both operations will determine the file name the same way.