HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Find a specific Substring

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
substringspecificfind

Problem

I'm writing a little Downloader that will look through directories online and download the content. The first prototype of my program is a success, now I just want to refine it and learn some more C#. The task is this:

Take this string:

http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/

and create the substring between the last two /

Result: All%20Ends%20In%20Silence

I find my current code brutish and probably not a clean, C# way of solving the problem:

string GetDirectoryName(string directory)
    {
        int lastIndex  = directory.LastIndexOf("/");
        int count = directory.Count(elem => elem == '/') - 1;

        int startIndex = 0;
        while (count > 0)
        {
            startIndex = directory.IndexOf("/", startIndex) + 1;
            --count;
        }

        return directory.Substring(startIndex, lastIndex - startIndex).Replace("%20", " ");
    }


Please advise me how I could make this code cleaner, clearer and following the C# methodology of programming.

Solution

The .NET framework will do this for you pretty cleanly with the right classes.

For example:

string url = "http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/";

DirectoryInfo di = new DirectoryInfo( new Uri(url).LocalPath );


The di.Name property contains "All Ends In Silence".

Code Snippets

string url = "http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/";

DirectoryInfo di = new DirectoryInfo( new Uri(url).LocalPath );

Context

StackExchange Code Review Q#4924, answer score: 10

Revisions (0)

No revisions yet.