diff --git a/src/Zio.Tests/TestUPathExtension.cs b/src/Zio.Tests/TestUPathExtension.cs new file mode 100644 index 0000000..b778875 --- /dev/null +++ b/src/Zio.Tests/TestUPathExtension.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace Zio.Tests +{ + public class TestUPathExtension + { + + + [Theory] + [InlineData("/a/b", "a", "b")] + [InlineData("/a/b/c", "a", "b/c")] + [InlineData("a/b", "a", "b")] + [InlineData("a/b/c", "a", "b/c")] + [InlineData("", "", "")] + [InlineData("/z","z","")] + + public void TestGetFirstDirectory(string path, string expectedFirstDir, string expectedRest) + { + var pathInfo = new UPath(path); + var firstDir = pathInfo.GetFirstDirectory(out var rest); + Assert.Equal(expectedFirstDir,firstDir); + Assert.Equal(expectedRest,rest); + } + } +} + diff --git a/src/Zio/UPathExtensions.cs b/src/Zio/UPathExtensions.cs index 84fbf10..7f0a616 100644 --- a/src/Zio/UPathExtensions.cs +++ b/src/Zio/UPathExtensions.cs @@ -88,14 +88,15 @@ public static string GetFirstDirectory(this UPath path, out UPath remainingPath) string firstDirectory; var fullname = path.FullName; - var index = fullname.IndexOf(UPath.DirectorySeparator, 1); + var offset = path.IsRelative ? 0 : 1; + var index = fullname.IndexOf(UPath.DirectorySeparator, offset); if (index < 0) { - firstDirectory = fullname.Substring(1, fullname.Length - 1); + firstDirectory = fullname.Substring(offset, fullname.Length - offset); } else { - firstDirectory = fullname.Substring(1, index - 1); + firstDirectory = fullname.Substring(offset, index - offset); if (index + 1 < fullname.Length) { remainingPath = fullname.Substring(index + 1); @@ -265,4 +266,4 @@ public static UPath AssertAbsolute(this UPath path, string name = "path") return path.FullName; } } -} \ No newline at end of file +}