Skip to content

Commit 564260b

Browse files
authored
Update Path.GetDirectoryName Snippet3 (#10853)
the current docs are outdated to NRT and confuse quotes 1. variable should be type string? not string 2. uses old-style format string (new would use interpolated syntax) 3. filepath reassignment should use conditional syntax 4. results suggest using single-quote [i.e. char not string], ugh 5. the final returned result is null but demo output shows '' which is factually visually correct but confusingly indistinuishable from "" emptystring I propose replacement C# code for this Snippet3
1 parent 51a7d8e commit 564260b

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -61,31 +61,30 @@ public void Combine()
6161
public void GetDirectoryName()
6262
{
6363
// <Snippet3>
64-
string filePath = @"C:\MyDir\MySubDir\myfile.ext";
65-
string directoryName;
66-
int i = 0;
67-
68-
while (filePath != null)
69-
{
70-
directoryName = Path.GetDirectoryName(filePath);
71-
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
72-
filePath, directoryName);
73-
filePath = directoryName;
74-
if (i == 1)
75-
{
76-
filePath = directoryName + @"\"; // this will preserve the previous path
77-
}
78-
i++;
79-
}
80-
/*
81-
This code produces the following output:
82-
83-
GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
84-
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
85-
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
86-
GetDirectoryName('C:\MyDir') returns 'C:\'
87-
GetDirectoryName('C:\') returns ''
88-
*/
64+
string? filePath = @"C:\MyDir\MySubDir\myfile.ext";
65+
string? directoryName;
66+
int i = 0;
67+
68+
while (filePath != null)
69+
{
70+
directoryName = Path.GetDirectoryName(filePath);
71+
Console.WriteLine($"GetDirectoryName(\"{filePath}\") returns {directoryName ?? "NULL"}");
72+
73+
filePath = (i == 1)
74+
? directoryName + @"\" // this will preserve the previous path
75+
: directoryName;
76+
77+
i++;
78+
}
79+
/*
80+
This code produces the following output:
81+
82+
GetDirectoryName("C:\MyDir\MySubDir\myfile.ext") returns C:\MyDir\MySubDir
83+
GetDirectoryName("C:\MyDir\MySubDir") returns C:\MyDir
84+
GetDirectoryName("C:\MyDir\") returns C:\MyDir
85+
GetDirectoryName("C:\MyDir") returns C:\
86+
GetDirectoryName("C:\") returns NULL
87+
*/
8988
// </Snippet3>
9089

9190
Console.WriteLine();
@@ -378,4 +377,4 @@ public static void Main()
378377
pathSnippets.HasExtension();
379378
pathSnippets.IsPathRooted();
380379
}
381-
}
380+
}

0 commit comments

Comments
 (0)