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".
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".
If you've definitely got an absolute path, use Path.GetDirectoryName(path).
If you might only get a relative name, use new FileInfo(path).Directory.FullName.
Note that Path and FileInfo are both found in the namespace System.IO.
You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.
If you're doing other things with the path, the FileInfo class may have advantages.
In my case, I needed to find the directory name of a full path (of a directory) so I simply did:
var dirName = path.Split('\\').Last();