Abraham
Abraham

Reputation: 1259

How to get directory of selected file?

I have a program where a user selects a file with an OpenFileDialog, I store that path (ofd.FileName) into a string FilePath, I need to get the name of the folder that the file is in, how do I do that?

Like if user selects file "C:\Users\Name\Documents\hi.txt", how do I get the folder path "C:\Users\Name\Documents" ?

Upvotes: 2

Views: 1966

Answers (1)

Steve
Steve

Reputation: 216243

The Path class offers numerous methods to handle File and Path strings
In your case you need to use

string fullFilePath = @"C:\Users\Name\Documents\hi.txt";
string pathOnly = Path.GetDirectoryName(fullFilePath);
Console.WriteLine(pathOnly);

Upvotes: 8

Related Questions