我正在尝试在 MonoGame 中加载图片(没有 Content.Load),但是当我尝试启动该项目时,我遇到了 System.IO.FileNotFoundException,我希望有人能告诉我我做错了什么.
错误消息:System.IO.FileNotFoundException:'无法在\ Debug中找到文件'G:\ Min enhet \ C#\ FirstMonoGameProject etcoreapp3.1\Content\Graphic\CoolBox'.'
我收到错误的代码
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;
}
}
我调用方法的附加代码(均来自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) ,这样就不会抛出异常。
首先,我在.Net 8.0 中遇到此错误。为了纠正错误,应将要打开的文件扔到项目文件夹中的bin文件夹中的debug文件夹中。之后,如果将其扔进net8.0并运行该项目,则可以获得健康的结果。
还要检查您的实际文件名。当您转到文件的属性并且名称被称为
test.txt
时,实际文件名是 test.txt.txt
。例如,当通过资源管理器创建文件时,请始终写入不带扩展名的名称。只要能帮助别人就好了