tags:

views:

127

answers:

3

Is there anything built into System.IO.Path that gives me just the filepath?

For example, if I have a string @"c:\webserver\public\myCompany\configs\promo.xml", is there any BCL method that will give me "c:\webserver\public\myCompany\configs\"?

+5  A: 

Path.GetDirectoryName()... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).

You could validate first by testing File.Exists() and/or Directory.Exists() on your path first to see if you need to call Path.GetDirectoryName

Andrew Barber
There's no need to call `File.Exists()`. Indeed, it's rather counter-productive in the case where your reason for finding the directory name is to create it if it doesn't already exist.
Jon Hanna
His example explicitly notes a path with a file name. If that is the pattern of the paths he is testing, and if those paths represent existing files, checking File.Exists() surely would be useful, would you not agree? Because the situation could be otherwise, of course, I was just suggesting he 'could' use the Exists methods on File and/or Directory; obviously, as appropriate for his situation.
Andrew Barber
Yes, a path with a file name. There's nothing in that to indicate a file exists, as file names come first.
Jon Hanna
As I said; it's an option and it may help depending on what is known about the path. Or it may not be necessary at all. But testing File.Exists() and Directory.Exists() on the same path is a quick and easy way to know if a path, which exists, is a file or directory.
Andrew Barber
A: 

Console.WriteLine( Path.GetDirectoryName(@"C:\hello\my\dear\world.hm"));

mumtaz
A: 

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

Jon Hanna