I have a string value which is /Images/She.jpg
. I want only the part after the /images/
i.e She.jpg
. How to extract that part into a string?
6 Answers
string filename = System.IO.Path.GetFileName("/Images/She.jpg");

- 27,184
- 6
- 59
- 66
-
Can you tell me how to delete that file. – vinay teja reddy Aug 16 '13 at 15:40
-
1Sure, you can use [System.IO.File.Delete](http://msdn.microsoft.com/en-US/library/system.io.file.delete.aspx) method to remove it. – Zbigniew Aug 16 '13 at 15:42
-
Though, make sure that the `path` is correct. – Zbigniew Aug 16 '13 at 15:44
-
So it Does.'t delete the fodler ? it only deletes the file in that folder ? sorry just a small confusion.. – vinay teja reddy Aug 16 '13 at 15:44
-
Yes, it'll only delete file, if you want to delete folder then you need to use `System.IO.Directory.Delete` – Zbigniew Aug 16 '13 at 15:45
If you're working with paths you should use the other answers. If it's only a plain string you're working with you can use following code:
string filePath = "/Images/She.jpg";
string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1);

- 14,186
- 6
- 41
- 72
-
Even when working with plain strings, you should use the `Path` class. What happens here if the file you were given is relative to the current directory, such as `"She.jpg"`? – dlras2 Aug 17 '13 at 19:27
This will work, as long as you don't have anything too complicated in your path, e.g. query parameters after the file name.
Path.GetFileName("/Images/She.jpg")

- 55,448
- 7
- 96
- 122
I like the GetFileName answers previously posted.
Alternatively, you can parse the string manually using IndexOf and Substring. I've included multiple variables so it's easy to see the steps of parsing a string.
var source = "/images/she.jpg";
var key = "/images/";
var target = source.IndexOf(key);
var start = target + key.Length;
var length = source.Length - start;
var result = source.Substring(start, length);

- 910
- 4
- 9
Just for fun, you could also split the string into an array and get the last element in the array...
string path = "/Images/She.jpg";
string[] arr = path.Split('/');
string filename = arr[arr.Length - 1];
or if you prefer a one liner
string path = "/Images/She.jpg";
string filename = path.Split('/').Last();
this will return
She.jpg

- 29,468
- 21
- 78
- 92
Well, you can move backwards from the end of the string.
private string GetFileName(string path)
{
string filename = null;
for (int i = (path.Length - 1); i > -1; --i)
{
if (path[i].ToString() == "/")
{
for (int x = (i + 1); x < (path.Length); ++x)
{
filename += path[x];
}
break;
}
}
return (filename);
}
This works backwards from the last char of the string until it hits a '/'. Then, it adds up all the characters after the '/' and returns that to you.

- 359
- 2
- 16