84

I'm writing a little utility that starts with selecting a file, and then I need to select a folder. I'd like to default the folder to where the selected file was.

OpenFileDialog.FileName returns the full path & filename - what I want is to obtain just the path portion (sans filename), so I can use that as the initial selected folder.

    private System.Windows.Forms.OpenFileDialog ofd;
    private System.Windows.Forms.FolderBrowserDialog fbd;
    ...
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        string sourceFile = ofd.FileName;
        string sourceFolder = ???;
    }
    ...
    fbd.SelectedPath = sourceFolder; // set initial fbd.ShowDialog() folder
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       ...
    }

Are there any .NET methods to do this, or do I need to use regex, split, trim, etc??

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
Kevin Haines
  • 2,492
  • 3
  • 18
  • 19

6 Answers6

116

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath);
Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
  • 5
    Thanks - it had to be a simple answer. Note to self: coding after midnight is not recommended. Reading more than just the method prototype also helps, as the VS documentation lists this as public static string GetDirectoryName(string path) & I misinterpreted the parameter. – Kevin Haines Jan 13 '09 at 21:27
32

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
Jan Macháček
  • 612
  • 7
  • 11
18
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Max
  • 197
  • 1
  • 2
  • 2
    Does initial directory change when the user selects a file? If not, then this approach would cause a problem when the user changes directory. Also, I don't think he wanted the `FileName` as part of his `sourceFolder`. – Brian J Jun 19 '13 at 17:22
10

You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.

FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";

if (browser.ShowDialog() == DialogResult.OK)
{
  tempPath  = browser.SelectedPath; // prints path
}
Mafii
  • 7,227
  • 1
  • 35
  • 55
Shaahin
  • 1,195
  • 3
  • 14
  • 22
0

Here's the simple way to do It !

string fullPath =openFileDialog1.FileName;
string directory;
directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
Abdel
  • 1
0

This was all I needed for the full path to a file

@openFileDialog1.FileName
WiiLF
  • 304
  • 3
  • 11