Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit a5247ca

Browse files
committed
Add alternative GetExtension() extension equivalent to Path.GetExtension()
1 parent 55c2780 commit a5247ca

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,8 @@ public static string[] SplitOnLast(this string strVal, string needle)
381381

382382
public static string WithoutExtension(this string filePath)
383383
{
384-
if (String.IsNullOrEmpty(filePath)) return null;
384+
if (string.IsNullOrEmpty(filePath))
385+
return null;
385386

386387
var extPos = filePath.LastIndexOf('.');
387388
if (extPos == -1) return filePath;
@@ -390,6 +391,15 @@ public static string WithoutExtension(this string filePath)
390391
return extPos > dirPos ? filePath.Substring(0, extPos) : filePath;
391392
}
392393

394+
public static string GetExtension(this string filePath)
395+
{
396+
if (string.IsNullOrEmpty(filePath))
397+
return null;
398+
399+
var extPos = filePath.LastIndexOf('.');
400+
return extPos == -1 ? string.Empty : filePath.Substring(extPos);
401+
}
402+
393403
static readonly char[] DirSeps = new[] { '\\', '/' };
394404

395405
public static string ParentDirectory(this string filePath)

tests/ServiceStack.Text.Tests/StringExtensionsTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,19 @@ public void Does_not_alter_filepath_without_extension()
8282
Assert.That("path/to/file.ext".WithoutExtension(), Is.EqualTo("path/to/file"));
8383
}
8484

85+
[TestCase(null, null)]
86+
[TestCase("/", "")]
87+
[TestCase("/a", "")]
88+
[TestCase("/a.b", ".b")]
89+
[TestCase("/a.b.c", ".c")]
90+
[TestCase("/{a.b}.c", ".c")]
91+
[TestCase("/:=#%$@{a.b}.c", ".c")]
92+
public void Does_get_Path_extension(string actual, string expected)
93+
{
94+
Assert.That(actual.GetExtension(), Is.EqualTo(Path.GetExtension(actual)));
95+
Assert.That(actual.GetExtension(), Is.EqualTo(expected));
96+
}
97+
8598
// 0 1
8699
// 01234567890123456789
87100
[TestCase("text with /* and <!--", "<!--", "/*", 10)]

0 commit comments

Comments
 (0)