Path.GetDirectoryName method in C#

In this article I will explain Path.GetDirectoryName method in C#.
  • 7789


C# path is a name of a directory which identify a unique location of a file in a file system. A path of a file system is expressed in a string of character. Path.GetDirectoryName method is a type of c# path. Path.GetDirectoryName Returns the directory information for the specified path string. Path.GetDirectoryName finds a directory name from a path. We look at this .NET framework method.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

class Program


    static void Main()


    string filePath = @"C:\rahul\rahulpics\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 + @"\"








 In this example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryNamemethod will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".

 The output of the following program


© 2020 DotNetHeaven. All rights reserved.