C#: Simple .NET Console App To Loop Through CSV, Download Images

I recently had the need to write a .NET console app which opens up a CSV file and does some stuff. This app loops through each row, downloads an image from the URL in column two and saves it with a unique file name provided in column one.

I want to remember this. So here it is.

using System;
using System.IO;
using System.Net;

namespace Download_Images
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				string root = @"C:";
					
				Console.WriteLine("Press any key to start.");
				Console.ReadLine();

				string[] records = File.ReadAllLines(root + "urls.csv");

				string destination = root + @"images";

				foreach (string record in records)
				{
					string[] fields = record.Split(',');
					string guid = fields[0];
					string imageUrl = fields[1];
					WebClient fileReader = new WebClient();
					string newFile = destination + guid + ".jpg";

					Console.WriteLine("Starting download: " + imageUrl);

					try
					{
						if (!File.Exists(newFile))
						{
							fileReader.DownloadFile(imageUrl.Trim(), newFile);
							Console.WriteLine("File saved: " + newFile);
						}
						else
						{
							Console.WriteLine("File exists. Skipping. " + guid + ".jpg");
						}

					}
					catch (Exception ex) {
						Console.WriteLine("Failed: " + ex.Message);
						if (ex.InnerException != null)
						{
							Console.WriteLine("Inner Exception: " + ex.InnerException.Message);
						}
					}

					Console.WriteLine();
				}

				Console.WriteLine("All done. Press any key to exit.");
				Console.ReadLine();
			}
			catch (Exception ex) {
				Console.WriteLine("There was an exception:");
				Console.WriteLine(ex.Message);

			}
		}
	}
}

Posted in: Code Samples, Development  |  Tagged with: , ,  |  Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*