Get full path without filename from path that includes filename

C#FilePath

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

    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

Solution 5 - C#

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;

Solution 6 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCantSleepAgainView Question on Stackoverflow
Solution 1 - C#Andrew BarberView Answer on Stackoverflow
Solution 2 - C#explorerView Answer on Stackoverflow
Solution 3 - C#Jon HannaView Answer on Stackoverflow
Solution 4 - C#Kobie WilliamsView Answer on Stackoverflow
Solution 5 - C#kevinwaiteView Answer on Stackoverflow
Solution 6 - C#KaramView Answer on Stackoverflow