user1559618
user1559618

Reputation: 469

Delete filename from a filepath in C#

I am trying to remove the filename of a path e.g.:

/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx

Would result in:

/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/

Bearing in mind that the file name might change, would a regex be the best way of achieving this?

Upvotes: 0

Views: 185

Answers (7)

Simon MᶜKenzie
Simon MᶜKenzie

Reputation: 8664

This is a fairly heavy approach, but sometimes it's nice to know you're using a bulletproof technique...

var path = new UriBuilder("file", "/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx");
var parent = new Uri(path.Uri, "..");

 Console.WriteLine(parent.AbsolutePath);

Result:

 /vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/

Upvotes: 2

M. Mennan Kara
M. Mennan Kara

Reputation: 10222

Actually, Path.GetDirectoryName will /'s to \'s.

var filepath = "/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx";
var directorypath = filepath.Substring(0, filepath.LastIndexOf("/", StringComparison.Ordinal) + 1);
// /vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/
var dir = Path.GetDirectoryName(filepath);
// \vmfs\volumes\50153b66-6aac5486-e942-080027a10080\TestMachine

Upvotes: 3

Stack User
Stack User

Reputation: 1398

strPath = "/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx";

string[] strFileParts = strPath.Split( '\\' );
if ( strFileParts.Length > 0 )
{
    str =  strFileParts[strFileParts.Length - 1] );
}

result = full_path - str;

Upvotes: 1

eyossi
eyossi

Reputation: 4330

You can use

Path.GetDirectoryName()

more info at: http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx

Upvotes: 3

ZafarYousafi
ZafarYousafi

Reputation: 10840

Use System.IO.Path.GetDirectoryName

System.IO.Path.GetDirectoryName("/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx")

Upvotes: 2

bytecode77
bytecode77

Reputation: 14820

There is a method in System.IO.Path for that

Path.GetDirectoryName(fileName)

Upvotes: 2

Embedd_0913
Embedd_0913

Reputation: 16555

You may use:

Path.GetDirectoryName(path);

Upvotes: 6

Related Questions