views:

1307

answers:

5

What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.

string filename = "C:\MyDirectory\MyFile.bat"

In this example, I should get "C:\MyDirectory".

+8  A: 

If you're definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullPath.

Jon Skeet
You just type to fast!
Grzenio
Indeed, but is there a method called GetDirectory? Isn't it GetDirectoryName?
Brandon
Yup, but that wasn't right anyway. Fixed :)
Jon Skeet
You can just use DirectoryName instead of Directory.FullPath can you not?
Steven Robbins
I was proofing against receiving a relative name. I hadn't spotted that the path will be absolute. I've now got both versions :)
Jon Skeet
Agile answering.. answer, refactor, refactor, refactor ;-)
Steven Robbins
Do you use snippy to check that? ;)
shahkalpesh
@shahkalpesh: Funnily enough, I haven't been using Snippy for SO. I should though!
Jon Skeet
+2  A: 
Path.GetDirectoryName(filename);
Grzenio
+2  A: 

You can use Path.GetDirectoryName and just pass in the filename.

MSDN Link

Brandon
+3  A: 
System.IO.Path.GetDirectoryName(filename)
Cherian
+3  A: 

You can use System.IO.Path.GetDirectory(filename), or turn the path into a FileInfo, and use fileInfo.Directory.

If you're doing other things with the path, the FileInfo may have advantages.

Reed Copsey