priyanka.sarkar
priyanka.sarkar

Reputation: 26538

How to get the root directory

I have a file path as

D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source\xyz.txt

If I do

Path.GetDirectoryName(fileName)

I get

D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source

But I want to get only the root directory i.e. "D:\\"

How can I get it?

N.B.~ Is it possible without string splitting?

Upvotes: 1

Views: 6945

Answers (5)

Bhushan Firake
Bhushan Firake

Reputation: 9458

You can use Path.GetPathRoot Method for this.

  • This method gets the root directory information of the specified path.
  • It returns the root directory of path, such as "C:\", or null if path is null, or an empty string if path does not contain root directory information.

So, you can simply have string root = Path.GetPathRoot(fullFileName);

But, this method does not verify that the path or file name exists.

Possible patterns for the string returned by this method are on MSDN as follows:

  • An empty string (path specified a relative path on the current drive or volume).
  • "/" (path specified an absolute path on the current drive).
  • "X:" (path specified a relative path on a drive, where X represents a drive or volume letter).
  • "X:/" (path specified an absolute path on a given drive).
  • "\\ComputerName\SharedFolder" (a UNC path).

Upvotes: 1

Jayram
Jayram

Reputation: 19588

String pathname= @"D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source\xyz.txt";    
string root = Path.GetPathRoot(pathname); 

Upvotes: 3

Ken Kin
Ken Kin

Reputation: 4703

You're in luck, there're several ways to do the same thing. Here're two of them:

  1. Path.GetRootPath as other answers already shown

  2. DirectoryInfo.Root property of FileInfo class:

    var fileName=
        @"D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source\xyz.txt";
    
    var file=new FileInfo(fileName);
    var root=file.Directory.Root;
    

Upvotes: 2

Ramesh Durai
Ramesh Durai

Reputation: 2686

Directory.GetDirectoryRoot Method

Upvotes: 3

Habib
Habib

Reputation: 223392

Use Path.GetPathRoot method provided by the framework

Gets the root directory information of the specified path

For your case you can use:

string rootPath = Path.GetPathRoot(filename);

Upvotes: 6

Related Questions