4

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?

Ian G
  • 29,468
  • 21
  • 78
  • 92
vinay teja reddy
  • 259
  • 1
  • 4
  • 12

6 Answers6

16
string filename = System.IO.Path.GetFileName("/Images/She.jpg");
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
5

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);
Abbas
  • 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
0

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")
Tim S.
  • 55,448
  • 7
  • 96
  • 122
0

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);
JeremiahDotNet
  • 910
  • 4
  • 9
0

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
Ian G
  • 29,468
  • 21
  • 78
  • 92
-1

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.

Rohan
  • 359
  • 2
  • 16