Skip to content

Commit

Permalink
Throw Exception In Content.Load When assetName Is A Rooted Path. (M…
Browse files Browse the repository at this point in the history
…onoGame#8569)

Fixes MonoGame#8568 


### Description of Change
Adds a `Path.IsRootedPath` check on the `assetName` parameter, and if it
is a rooted path, throws a `ContentLoadException` with a clear exception
message on why the exception occurred.

Previous behavior would have allowed a rooted path as the `assetName`
parameter which would later throw a `FileNotFoundException` in the
`ContentManager.OpenStream` method when attempting to open the stream.
This is due to how `Path.Combine` works, where if the second parameter
is a rooted path, it ignores the first parameter.

While technically the `FileNotFoundException` is correct when the stream
is attempted to open, the exception doesn't clearly describe to the
developer why it occurred. The `assetName` parameter is defined as being
a relative path, so if it is a rooted path, the exception should be
thrown earlier to tell the developer they used a rooted path and need to
use a relative path instead.
<!-- 
Enter description of the fix in this section.
Please be as descriptive as possible, future contributors will need to
know *why* these changes are being made.
For inspiration review the commit/PR history in the MonoGame repository.
-->
  • Loading branch information
AristurtleDev authored Nov 12, 2024
1 parent fb03c0a commit f0bffd4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions MonoGame.Framework/Content/ContentManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,10 @@ public virtual T Load<T>(string assetName)
{
throw new ObjectDisposedException("ContentManager");
}
if(Path.IsPathRooted(assetName))
{
throw new ContentLoadException("assetName '" + assetName + "' cannot be a rooted (absolute) path. Remove any leading drive letters (e.g. 'C:'), forward slashes or backslashes");
}

T result = default(T);

Expand Down
21 changes: 21 additions & 0 deletions Tests/Framework/Content/ContentManagerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using NUnit.Framework;

namespace MonoGame.Tests.Content
{
public class ContentManagerTest
{
[TestCase("C:\\image.png")]
[TestCase("\\image.png")]
[TestCase("/image.png")]
public void ThrowExceptionIfAssetNameIsRootedPath(string assetName)
{
GameServiceContainer services = new GameServiceContainer();
ContentManager content = new ContentManager(services, "Content");
var exception = Assert.Throws<ContentLoadException>(() => content.Load<Texture2D>(assetName));
StringAssert.Contains("rooted (absolute)", exception.Message);
}
}
}

0 comments on commit f0bffd4

Please sign in to comment.