Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full path without filename from path that includes filename

Tags:

c#

file

path

People also ask

How do I get the full path of a filename?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

Does full path include filename?

Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.

How can I find the filename without path?

Use the substring() method to get the filename without the path, e.g. fullPath. substring(fullPath. lastIndexOf('/') + 1) . The substring method will return a new string containing only the characters after the last slash.

Which property is used to get the full path of the file?

The FullName property returns just the full path of a file including the file name.


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


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

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.


    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


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;

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));
        }
    }
}