CantSleepAgain
CantSleepAgain

Reputation: 3873

Get full path without filename from path that includes filename

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\"?

Upvotes: 265

Views: 341806

Answers (7)

Orien
Orien

Reputation: 77

A file or directory may not always be on disk. better than File.Exists() and/or Directory.Exists() conditions, we can use:

/// <summary> Determine if given path is file </summary>
public static bool IsFile(string path) => !IsDirectory(path);
/// <summary> Determine if given path is directrory </summary>
public static bool IsDirectory(string path) {

    return String.IsNullOrEmpty(Path.GetExtension(path));
}

Upvotes: 0

kevinwaite
kevinwaite

Reputation: 649

Use GetParent() as shown, works nicely. Add error checking as you need.

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

Upvotes: 9

Kobie Williams
Kobie Williams

Reputation: 470

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

    string currentDirectory = Path.GetDirectoryName(fileAndPath);

    string fullPathOnly = Path.GetFullPath(currentDirectory);

currentDirectory: c:\webserver\public\myCompany\configs

fullPathOnly: c:\webserver\public\myCompany\configs

Upvotes: 31

explorer
explorer

Reputation: 12110

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

Upvotes: 86

Karam
Karam

Reputation: 97

I used this and it works well:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

Upvotes: 4

Jon Hanna
Jon Hanna

Reputation: 113382

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.

Upvotes: 52

Andrew Barber
Andrew Barber

Reputation: 40160

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

Upvotes: 305

Related Questions