LuMa
LuMa

Reputation: 1763

How to get the substring after a given string

I'm new to C# and struggle with string parsing. I have a string like this:

C:\User\Max\Pictures\

And I got multiple file paths:

C:\User\Max\Pictures\car.jpg
C:\User\Max\Pictures\trains\train.jpg

How can I strip the base path from those file paths to get:

car.jpg
trains\train.jpg

Something like this failed:

string path = "C:\\User\\Max\\Pictures\\";
string file = "C:\\User\\Max\\Pictures\\trains\\train.jpg";

string newfile = file.Substring(file.IndexOf(path));

Upvotes: 0

Views: 333

Answers (3)

René Vogt
René Vogt

Reputation: 43876

You want to get the substring of file after the length of path:

string newfile = file.Substring(path.Length);

Note that it's a good idea to use Path methods like Path.GetFileName() when dealing with file paths (though it's not good applyable to the "train" example).

Upvotes: 4

lordkain
lordkain

Reputation: 3109

There are special classes to handle filepaths

var filePath = new FileInfo("dd");

In filePath.Name is the filename of the file whitout directory

So for your scenario you want to strip base dir. So you can do this

var filePath = new FileInfo(@"c:\temp\train\test.xml");
var dir = filePath.FullName.Replace(@"c:\temp", String.Empty);

Upvotes: 0

Irwene
Irwene

Reputation: 3025

The other answer would be to replace your path with an empty string :

string filePath = file.Replace(path, "");

Upvotes: 1

Related Questions