I'm trying to load a picture in MonoGame (without Content.Load), But when I try to launch the project I encounter the System.IO.FileNotFoundException and I was hoping someone could tell me what I'm doing wrong.
Error message: System.IO.FileNotFoundException: 'Could not find file 'G:\Min enhet\C#\FirstMonoGameProject\bin\Debug\netcoreapp3.1\Content\Graphic\CoolBox'.'
The code where I get the error
public Texture2D LoadTexture()
{
string fullPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
"/Content/Graphic/" "CoolBox";
using (FileStream fileStream = File.Open(fullPath, FileMode.Open))
{
Texture2D myTexture2D = Texture2D.FromStream(EntityManager.graphicsDevice, fileStream);
return myTexture2D;
}
}
Additional code where I call on the method (both from game1)
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
coolBox.LoadTexture();
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(coolBox.LoadTexture(), new Rectangle(0, 0, 280, 210), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
Thanks in advanced!
CodePudding user response:
First I would add checking for the file existence using
File.Exists(String)
method.
Also I found helpful is to use Path.Combine()
method to properly create a path instead of manually concatenating strings.
CodePudding user response:
System.IO.FileNotFoundException appears when the path that you are using is wrong , it means that the file doesnt exist. Your problem cames on the variable string fullpath wich has a wrong path.
First check on your computer(windows search : windows s) that the file exists by copying there the full path. Anyway to prevent this exception you can use try catch block to display a message if the file dont exists. Other solution can be using File.Exists(path) , this way you dont throw an exception.