Coder Perfect

From a route that includes a filename, get the whole path without the filename.


Is there a method in System.IO.Path that merely returns the filepath?

If I have a string, for example,

Is there a BCL method that will provide me with the information I need?

Asked by CantSleepAgain

Solution #1

Path.GetDirectoryName()… but make sure the path you’re feeding it has a file name; it just removes the last bit of the path, whether it’s a file name or a directory name (it actually has no idea which).

You may start by putting File to the test. Exists() and/or Directory are both valid options. To see if you need to call Path, first run Exists() on your path. GetDirectoryName

Answered by Andrew Barber

Solution #2


Answered by explorer

Solution #3

Path. GetDirectoryName() returns the directory name, thus you could use Path instead (without the trailing reverse solidus character). Path.DirectorySeparatorChar + GetDirectoryName(filePath).

Answered by Jon Hanna

Solution #4

    string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";

    string currentDirectory = Path.GetDirectoryName(fileAndPath);

    string fullPathOnly = Path.GetFullPath(currentDirectory);

Answered by Kobie Williams

Solution #5

As illustrated, GetParent() is a good choice. As needed, add error checking.

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;

Answered by kevinwaite

Post is based on