Thursday, November 13, 2025

Uri.TryCreate Cross-Platform Quirk: Windows vs. Linux

Hope everyone’s having fun with .NET 10, C# 14 and Visual Studio 2026 from the .NET Conf 2025 announcements.

I was upgrading a project to .NET 10 and as part of the upgrade, was doing some refactoring in the pipelines. One of the changes I did is, I moved the agent that is used to run tests from windows-latest to ubuntu-latest and a test started to fail.

After looking at the unit under test, at core it was checking a given string is a valid Web Uri.

In simple, it's something like this.

[Fact]
public void TryCreate_WhenNotAValidWebUri_ShouldNotCreate()
{
    const string uriString = "/somePath";
    bool isValidWebUri = Uri.TryCreate(uriString, UriKind.Absolute, out Uri? _);
    Assert.False(isValidWebUri);
}
If we run this on Windows, it's passing. Good, because obviously "/somePath" is not a Web Uri.
Windows: Pass
And on Linux, it's failing.
Linux: Fail
Apparently on Linux, 
"/somePath" is being treated as a valid Absolute Uri.

Updated the code as follows.

[Fact]
public void TryCreate_WhenNotAValidWebUri_ShouldNotCreate()
{
    const string uriString = "/somePath";

    bool isValidWebUri = Uri.TryCreate(uriString, UriKind.Absolute, out Uri? uri)
        && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);

    Assert.False(isValidWebUri);
}
Now it's passing in both Windows and Linux.
Linux: Pass
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment