如何解决System.IO.FileNotFoundException异常?



我试图在MonoGame中加载图片(没有Content.Load),但是当我试图启动项目时,我遇到了System.IO.FileNotFoundException我希望有人能告诉我我做错了什么。

错误信息:System.IO.FileNotFoundException: 'Could not find file 'G:Min enet c# FirstMonoGameProjectbinDebugnetcoreapp3.1ContentGraphicCoolBox'.'

我得到错误的代码

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;
}
}

我调用方法的附加代码(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);
}

首先,我将添加检查文件是否存在使用File.Exists(String)方法。另外,我发现有用的是使用Path.Combine()方法来正确创建路径,而不是手动连接字符串。

System.IO。FileNotFoundException出现时,你正在使用的路径是错误的,这意味着该文件不存在。你的问题出现在变量字符串fullpath上,它有一个错误的路径。

首先在您的计算机上(windows搜索:windows+s)通过复制完整路径来检查文件是否存在。无论如何,为了防止这个异常,你可以使用try catch块来显示一个消息,如果文件不存在。其他解决方案可以使用File.Exists(path),这样你就不会抛出异常。

还要检查您的实际文件名。当你进入文件的属性,文件名被称为,比如test.txt,那么实际的文件名是test.txt.txt。例如,当通过资源管理器创建文件时,总是写入没有扩展名的名称。只要它能帮助别人

最新更新