2
\$\begingroup\$
using System;
using System.Linq;
using RedditSharp;
using System.Net;
using RedditSharp.Things;

namespace reSharp
{
    class Program
    {
        public static void Main()
        {
            string sub = "/r/";
            string saveDir = @"SAVE_DIRECTORY";
            Console.WriteLine("Subreddit:");
            sub += Console.ReadLine();

            Console.WriteLine("Amount:");
            int amount = Convert.ToInt32(Console.ReadLine());
            amount += 1;

            Console.WriteLine("Time Period");
            string timePer = Console.ReadLine();

            Reddit reddit = new Reddit();
            var subreddit = reddit.GetSubreddit(sub);
            if (timePer == "all")
            {
                foreach (var post in subreddit.GetTop(FromTime.All).Take(amount))
                {
                    if (post.IsStickied || post.IsSelfPost || Convert.ToString(post.Url).Contains("reddituploads")) continue;
                    string postURL = Convert.ToString(post.Url);
                    DownloadImages(postURL, saveDir);

                }
            }
            else
            {
                if (timePer == "hot")
                {
                    foreach (var post in subreddit.Hot.Take(amount))
                    {
                        if (post.IsStickied || post.IsSelfPost || Convert.ToString(post.Url).Contains("reddituploads")) continue;
                        string postURL = Convert.ToString(post.Url);
                        DownloadImages(postURL, saveDir);

                    }
                }
            }

        }

        public static void DownloadImages(string imageURL, string userDir)
        {

            if (imageURL.Contains("gfycat.com"))
            {
                imageURL = imageURL.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";
            }

            if (imageURL.Contains(".gifv"))
            {
                imageURL = imageURL.Replace(".gifv", ".mp4");
            }

            Console.WriteLine("Downloading {0}", imageURL);
            string[] splitURL = imageURL.Split('/');
            int index = splitURL.Length - 1;
            string fileName = splitURL[index];
            WebClient client = new WebClient();
            try
            {
                client.DownloadFile(imageURL, userDir + fileName);
            }
            catch (Exception)
            {
                Console.WriteLine("[INFO] ERROR DOWNLOADING FILE");
            }
        }
    }
}

The program effectively just downloads pictures from a given reddit subreddit. How could this be tided? Thanks.

\$\endgroup\$
2
\$\begingroup\$

There are few things you can do. Start by encapsulating these lines

if (imageURL.Contains("gfycat.com"))
{
    imageURL = imageURL.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";
}

if (imageURL.Contains(".gifv"))
{
    imageURL = imageURL.Replace(".gifv", ".mp4");
}

in their own method. Let's call it FixImageUrl (this is C# 7)

public static string FixImageUrl(string imageUrl)
{
    switch (imageUrl)
    {
        case string url when url.Contains("gfycat.com"):
            return imageUrl.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";

        case string url when url.Contains(".gifv"):
            return imageUrl.Replace(".gifv", ".mp4");

        default: return imageUrl;
    }
}

string[] splitURL = imageURL.Split('/');
int index = splitURL.Length - 1;
string fileName = splitURL[index];

Then you can simplify this a little bit by using the Last extension:

var fileName = imageURL.Split('/').Last();

It probably doesn't matter here but it's a good habit to always dispose objects that are disposable. This means the WebClient requires special care.

You also want to know what went wrong so don't swallow the exception. Print either the message or log the entire exception.

When working with paths you should use the Path.Combine method to avoid any invalid paths like ones with missing \ etc.

try
{
    using (var client = new WebClient())
    {
        client.DownloadFile(imageURL, Path.Combine(userDir, fileName));
    }
}
catch (Exception ex)
{
    Console.WriteLine($"[INFO] ERROR DOWNLOADING FILE: {ex}");
}
\$\endgroup\$
  • \$\begingroup\$ This is great! Thank you so much, it's really helpful :) I'll try and put these into practise with future programs I make too :D \$\endgroup\$ – ocelot Feb 23 '17 at 18:01

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.