53

I have strings that have a directory in the following format:

C://hello//world

How would I extract everything after the last / character (world)?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
john cs
  • 2,220
  • 5
  • 32
  • 50

5 Answers5

75
string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"

The LastIndexOf method performs the same as IndexOf.. but from the end of the string.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • 3
    Since C# 8.0 you can also use the range operator. ```C# Console.WriteLine(path[pos..]); ``` For reference, see: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges – Kyle Jun 22 '20 at 09:34
  • 2
    Good thing to notice how this works when there is no slash in the string. It returns the whole string, which is usually correct. Also, the Substring method does not need the second parameter, it returns everything till the end of string automatically. – Palec Oct 21 '20 at 12:57
52

using System.Linq;

var s = "C://hello//world";
var last = s.Split('/').Last();
Matthew Steven Monkan
  • 8,170
  • 4
  • 53
  • 71
16

There is a static class for working with Paths called Path.

You can get the full Filename with Path.GetFileName.

or

You can get the Filename without Extension with Path.GetFileNameWithoutExtension.

Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • 1
    I had thought about that, but notice that the OP seems to not be focusing on a file, but a directory – Justin Pihony Apr 07 '13 at 02:51
  • Caution with this: it won't work if the filename contains a colon : e.g. //depot/some:file.ext GetFileName will only return file.ext which is not what you might expect. This is not a valid path on windows systems but the OP didn't specify the OS. – pangabiMC May 30 '18 at 16:55
  • @JustinPihony it does not matter if it is a file or directory. `Path.GetFileName("C://hello//world")` will return `world`. – Martin Schneider Nov 10 '22 at 15:39
11

Try this:

string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
Shreyash S Sarnayak
  • 2,309
  • 19
  • 23
Mohammad Rahman
  • 239
  • 3
  • 7
  • 2
    This is the same solution already posted by Simon Whitehead (http://stackoverflow.com/a/15857606/2029849), besides of an explicitly given length in the `Substring` method call. – abto Jan 14 '17 at 14:07
  • This is smarter solution instead @abto – Lali Dec 28 '17 at 10:15
6

I would suggest looking at the System.IO namespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property

var directoryName = new DirectoryInfo(path).Name;
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180