HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do I get the directory from a file's full path?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhowfullfromthefilepathget

Problem

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".

Solution

If you definitely have an absolute path, use Path.GetDirectoryName(path).

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

Note that Path and FileInfo are both found in the namespace System.IO.

Context

Stack Overflow Q#674479, score: 1067

Revisions (0)

No revisions yet.