[HOWTO] Using Path.Combine correctly to ensure cross-platform compatibility

I guess every .NET developer is familiar with the Path.Combine method. But, is every .NET developer using it correctly to ensure its result is cross-platform compatible? I guess no as I was one of these developers who didn’t use it correctly.

Did you ever see something like this?

C#
var arbitraryPath = Path.GetFullPath(
Path.Combine(
AppContext.BaseDirectory,
@"..\..\..\..\ArbitraryDirectory"
)
);

This works flawlessly on Windows. However, it fails on Linux.

System.IO.DirectoryNotFoundException : Could not find a part of the path '/home/vsts/work/1/s/src/WhateverProject/bin/Release/net10.0/..\..\..\..\ArbitraryDirectory'.

To make use of the full potential of Path.Combine make sure to let the method decide which delimiter to use based on the underlying operating system by using it properly!

C#
var arbitraryPath = Path.GetFullPath(
Path.Combine(
AppContext.BaseDirectory,
"..",
"..",
"..",
"..",
"ArbitraryDirectory"
)
);

Leave a Reply

Powered by WordPress.com.

Up ↑

Discover more from blog.rufer.be

Subscribe now to keep reading and get access to the full archive.

Continue reading