Tuesday, January 4, 2011

Randomize picture names

The following is a console application written in C# for randomizing names of jpg-files in the current directory and all sub directories. I made it so my mother can make pictures appear in random order on the digital picture frame I gave her last Christmas as it lacked that feature.

All output is in Swedish.
Download binary
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace se.gotling.tools
{
    class RandomizeFileNames
    {
        private static string extension = ".jpg";

        static void Main(string[] args)
        {
            string fullPath = System.Reflection.Assembly.GetAssembly(typeof(RandomizeFileNames)).Location;
            string directory = Path.GetDirectoryName(fullPath);

            Console.WriteLine("Katalog: {0}\n" ,directory);
            
            string[] fileNames = Directory.GetFiles(directory, "*" + extension, SearchOption.AllDirectories);
            if (fileNames.Length > 0)
            {
                Console.WriteLine("Hittade {0} filer med filändelsen {1}\n", fileNames.Length, extension);
            }
            else
            {
                Console.WriteLine("Inga filer hittades med filändelsen {0}\nTrycka på valfri tangent för att avsluta", extension);
                Console.ReadKey(true);
                return;
            }
            
            Console.WriteLine("Tryck \"r\" för att slumpa fram nya filnamn\n");
            if(!Console.ReadKey(true).Key.Equals(ConsoleKey.R))
            {
                Console.WriteLine("Avbröt ändring av filnamn. Trycka på valfri tangent för att avsluta");
                Console.ReadKey(true);
                return;
            }

            foreach (string fileName in fileNames)
            {
                string filePath = Path.GetDirectoryName(fileName);
                while (true)
                {
                    string newFileName = filePath + Path.DirectorySeparatorChar + Path.GetRandomFileName().Split('.')[1] + extension;
                    if (!File.Exists(newFileName))
                    {
                        File.Move(fileName, newFileName);
                        Console.WriteLine("Före: {0}\t Efter: {1}", fileName.Remove(0, directory.Length + 1), newFileName.Remove(0, directory.Length + 1));
                        break;
                    }
                }
                
            }
            Console.WriteLine("\n\nFärdig! Trycka på valfri tangent för att avsluta");
            Console.ReadKey(true);
        }
    }
}