diff --git a/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs b/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs index dedcdaae0bf..c53bfd1b1eb 100644 --- a/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs +++ b/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs @@ -61,31 +61,30 @@ public void Combine() public void GetDirectoryName() { // - string filePath = @"C:\MyDir\MySubDir\myfile.ext"; - string directoryName; - int i = 0; - - while (filePath != null) - { - directoryName = Path.GetDirectoryName(filePath); - Console.WriteLine("GetDirectoryName('{0}') returns '{1}'", - filePath, directoryName); - filePath = directoryName; - if (i == 1) - { - filePath = directoryName + @"\"; // this will preserve the previous path - } - i++; - } - /* - This code produces the following output: - - GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir' - GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir' - GetDirectoryName('C:\MyDir\') returns 'C:\MyDir' - GetDirectoryName('C:\MyDir') returns 'C:\' - GetDirectoryName('C:\') returns '' - */ + string? filePath = @"C:\MyDir\MySubDir\myfile.ext"; + string? directoryName; + int i = 0; + + while (filePath != null) + { + directoryName = Path.GetDirectoryName(filePath); + Console.WriteLine($"GetDirectoryName(\"{filePath}\") returns {directoryName ?? "NULL"}"); + + filePath = (i == 1) + ? directoryName + @"\" // this will preserve the previous path + : directoryName; + + i++; + } + /* + This code produces the following output: + + GetDirectoryName("C:\MyDir\MySubDir\myfile.ext") returns C:\MyDir\MySubDir + GetDirectoryName("C:\MyDir\MySubDir") returns C:\MyDir + GetDirectoryName("C:\MyDir\") returns C:\MyDir + GetDirectoryName("C:\MyDir") returns C:\ + GetDirectoryName("C:\") returns NULL + */ // Console.WriteLine(); @@ -378,4 +377,4 @@ public static void Main() pathSnippets.HasExtension(); pathSnippets.IsPathRooted(); } -} \ No newline at end of file +}