Click here to Skip to main content
16,018,419 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,

I am having below code and I want to display the file name with immediate folder name.


string filepath="test/abc/pqr/test1/test2/abxc.txt";


and I want to display only "/test2/abxc.txt";

the folder and sub folder names and count is decided at run time.

Please suggest.

Thanks.
Posted

Hi,

Till now I tried below code and this is also working for.

C#
string filepath="test/abc/pqr/test1/test2/abxc.txt";

var lastSlash= filepath .Substring(0, filepath .LastIndexOf("/"));

string secondLastSlash= filepath .Substring(lastSlash= .LastIndexOf("/") + 0);




Thanks.
 
Share this answer
 
v2
If you always want the string part starting from the second last '/', then do this:
1. Split[^] the full filepath into an array by '/'
2. then simply concatenate the last two elements of this array.
see example:
C#
using System;

public class Program
{
    public static void Main()
    {
        string filepath="test/abc/pqr/test1/test2/abxc.txt";

        // Split string on /.
        string[] parts = filepath.Split('/');
        int size = parts.Length;
        string result = "/" + parts[size - 2] + "/" + parts[size - 1];

        Console.WriteLine(result);

    }
}

which give you:
/test2/abxc.txt
 
Share this answer
 
v4
Comments
Rashmi Sutar 11-May-15 8:05am    
Thank you..
Its working fine :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900