4
\$\begingroup\$

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<char>(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.

\$\endgroup\$
10
\$\begingroup\$

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".

\$\endgroup\$
  • \$\begingroup\$ That's pretty useful. I'll have to look at the library on MSDN, thanks! \$\endgroup\$ – IAE Sep 20 '11 at 15:27
2
\$\begingroup\$

You could replace your loop with a call to LastIndexOf:

const char separator = '/';
int lastSlash = directory.LastIndexOf(separator);
int slashBeforeLast = directory.LastIndexOf(separator, lastSlash - 1);
return directory.Substring(slashBeforeLast + 1, lastSlash - slashBeforeLast - 1);
\$\endgroup\$
  • \$\begingroup\$ I am already getting the last '/' with LastIndexOf. How would a second call to LastIndexOf get me the other '/' I need? \$\endgroup\$ – IAE Sep 21 '11 at 15:45
  • \$\begingroup\$ @SoulBeaver: By adding an index. I've specifically linked to the overload that takes an index. I'm updating my answer with an example. \$\endgroup\$ – Hosam Aly Sep 21 '11 at 21:00
  • \$\begingroup\$ Aaaah now I understand what you mean, thanks! \$\endgroup\$ – IAE Sep 22 '11 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.