Downloaded Files Manager Tutorial

This is a self explained source code for a very useful tool, a downloaded files manager which will help you to bulk process your downloads, renaming the files for removing annoying chars and strings, years, and unwanted added comments as : ( by the big ripper ) from the file names, leaving you with the clean file names we all want.


In this tutorial you will have nice examples on how to work with :

  • Regular expressions

  • Splitting File path, name and extension

  • Recursing folders

  • Tooltips



Here is some code for you, check up the end of the page to download the whole solution


/*
 Downdloaded files manager Tutorial
 
 Author :   BlackRabbit ( Abel Carabajal )
 Date   :   2012-05-13
 Version:   0.1
 
 Purpose :
 
 Organize downloads, rename and Copy/move downloaded files from downloaders incoming
 files folders to designed repositories, and then Manage repositories, using file type
 criteria,
 and incrementaly compare and syncronize with back up repositories
 
 In next version :
 
 - File distribution to folders by file extension
 - File compare in between repositories
 - Repository to .csv file
 - File type config strings
 - Open / Save project
 
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace DownloadedFilesManager
{
        public partial class Form1 : Form
        {
                List<string> myFiles;

                public Form1()
                {
                        InitializeComponent();
                }

                private void Form1_Load(object sender, EventArgs e)
                {
                        /*create the toProcces's file list*/
                        myFiles = new List<string>();

                        // add the form's tooltips
                        // so new users get up to speed with the tool usage
                        toolTip1.SetToolTip(gbFileTypes, "Select here which kind of files do you want to be organizedncheck <all files if in general>nor video files if you want .avi, .mpg and general video files to be processed only");
                        toolTip1.SetToolTip(cbDeleteCor, "Remove any in-brackets content from file namen for example :nsource : [tvseries] spartacus 04.avinresult :
spartacus 04.avi ");
                        toolTip1.SetToolTip(cbDeletePar, "Remove any in-parenteshis content from file namen for example :nsource : spartacus 05 (the ripper's group).avinresult : spartacus 05.avi ");
                        toolTip1.SetToolTip(cbDeleteYear, "Remove years (from 1980 to 2019) from file namen for example :nsource : spartacus 06 2012.avinresult : spartacus 06.avi ");

                        toolTip1.SetToolTip(cbCharRemove, "Remove annoying chars from the file namen for example :nsource ~~Lord of the rings ~~-~~ the two towers avi: .avinresult : Lord of the rings - the two towers.avi");
                        toolTip1.SetToolTip(tbCharactersToRemove, "Remove annoying chars from the file namen for example :nsource ~~Lord of the rings ~~-~~ the two towers avi: .avinresult : Lord of the rings - the two towers.avi");

                        toolTip1.SetToolTip( lblDeleteStrings , "Remove annoying strings from the file namen for example :nyou choose to remove :  uploaded by the upload masternsource The matrix uploaded by the upload master.avi: .avinresult : The Matrix.avinyou can choose many strings using | as delimitern for example : uploaded by|rippers group|the greeen giantnand the system will remove any ocurrence of those strings");
                        toolTip1.SetToolTip(tbStringsToRemove, "Remove annoying strings from the file namen for example :nyou choose to remove :  uploaded by the upload masternsource The matrix uploaded by the upload master.avi: .avinresult : The Matrix.avinyou can choose many strings using | as delimitern for example : uploaded by|rippers group|the greeen giantnand the system will remove any ocurrence of those strings");

                        toolTip1.SetToolTip(cbReplaceBySpace, "Replace chars meant to be space from the file namen for example :nsource Lord.of.the.rings.-.the.two.towers.avi: .avinresult : Lord of the rings - the two towers.avi");
                        toolTip1.SetToolTip(tbReplaceWithSpace, "Replace chars meant to be space from the file namen for example :nsource Lord.of.the.rings.-.the.two.towers.avi: .avinresult : Lord of the rings - the two towers.avi");

                        toolTip1.SetToolTip(lbSourceFolders, "Press <add folder> and set the folders you want the system to work withnfor example :nc:emuleincomingnc:utorrentincomingnetc");

                        toolTip1.SetToolTip(cbVideoFiles, "Add video files (avi,mpg,etc) to the files-to-rename set");
                        toolTip1.SetToolTip(cbAudioFiles, "Add audio files (wav,mp3,etc) to the files-to-rename set");
                        toolTip1.SetToolTip(cbPictures, "Add picture files (jpg,png,etc) to the files-to-rename set");
                        toolTip1.SetToolTip(cbComics, "Add comic files (cbr,cbz,etc) to the files-to-rename set");
                        toolTip1.SetToolTip(cbZippedFiles, "Add zipped files (zip,rar,etc) to the files-to-rename set");
                        toolTip1.SetToolTip(cbDocuments, "Add document files (doc,xls,etc) to the files-to-rename set");

                }

                //
                // Opens a FolderBrowserDialog, selects a new folder
                // and Adds it to the folders list
                //
                private void btAddSourceFolder_Click(object sender, EventArgs e)
                {
                        FolderBrowserDialog newFolder = new FolderBrowserDialog();

                        if (newFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                                if (!lbSourceFolders.Items.Contains(newFolder.SelectedPath))
                                {
            &nbsp
;                           lbSourceFolders.Items.Add(newFolder.SelectedPath);
                                }
                        }
                }

                //
                // button Find and rename click action
                //  It is the action pilot, it takes one by one the
                //  folders selected and calls the folder process
                //
                private void btFindAndRename_Click(object sender, EventArgs e)
                {
                        // clear remaining files in the list since the last run
                        myFiles.Clear();
                        tbLog.Clear();

                        foreach (string directory in lbSourceFolders.Items)
                        {
                                // no directory, no proccess
                                if (!Directory.Exists(directory))
                                {
                                        lbSourceFolders.Items.Remove(directory);
                                        continue;
                                }

                                // lets process the folder
                                folderFilesToList(directory);
                        }

                        logToForm("- - - - - - - - - - - - - - - - - -");
                        logToForm(myFiles.Count.ToString() + " Files found ");
                        logToForm("- - - - - - - - - - - - - - - - - -");

                        // Lets go renaming
                        renameFromList();
                }

                //
                // Here we get the work done,
                //      we take the given folder, recurse its subdirectories
                //      and process the files according to the form criteria
                //
                private void folderFilesToList( string folder )
                {
                        // lets check up the folder for subfolders,
                        // it there is one we do some recursive process
                        foreach( string fsSubdir in Directory.GetDirectories( folder ) )
                        {
                                folderFilesToList(fsSubdir);
                        }

                        // Time to go trough the files,
                        // we filter them, if they are good to go we add it
                        // to the files to process list ( myFiles )
                        //
                        foreach( string file in Directory.GetFiles( folder ) )
                        {
                                // extension validation only when All Files checkbox is not checked
                                if ( !cbAllFiles.Checked )
                                {
                                        // Validates if the current file extension matches any of
                                        // the selected criteria
                                        // if it doesn't the file is skipped
                                        if (
                                                !validateFileExtension( file, cbAudioFiles, "(mp3|wav)" ) &&
                                                !validateFileExtension( file, cbVideoFiles, "(mpg|mp4|avi|mkv|ogm|divx)" ) &&
                                                !validateFileExtension( file, cbZippedFiles, "(rar|zip|gz)" ) &&
                                                !validateFileExtension( file, cbPictures, "(jpg|gif|png|ps|jpeg)" )  &&
                                                !validateFileExtension( file, cbComics, "(cbr|cbz)") &&
                                                !validateFileExtension( file, cbDocuments, "(pdf|doc|docx|xls|txt|xlsx|ppt|pps)" )
                                                )
                                        {
                                                continue;
                                        }
                                }

                                // if we reach this point the file is good to go
                                myFiles.Add(file);
                        }
                }

                //
                // Here we take a file, and apply the form selected criteria
                //  It returns true when the extension checks and the checkbox is checked
                //  it returns false otherwise
                private bool validateFileExtension(
                        string _file, /* the file name */
                        CheckBox _validator,  /* the form's checkbox, to know if the user cares or not of this file extension*/
                        string _fileExtensions /* the extension list to check against file extension */ )
                {
                       
                        // _filextensions comes already as a regular expresion on this format :
                        // ( extension 1|extension 2|extension 3) as in (avi|mpg|mkv)
                        //  which means : match if you find avi or (|) mpg or mkv in the string
                        //  which is the file extension we get by using Path.GetExtension
           
            //
                        if ( Regex.IsMatch(Path.GetExtension(_file), _fileExtensions, RegexOptions.IgnoreCase)
                        && _validator.Checked)
                        {
                                return true;
                        }

                        return false;
                }

                // Here we apply the renaming criteria
                //
                private void renameFromList()
                {
                        int renamingCounter = 0;
                        string newName = "";
                        foreach (string fileToRename in myFiles)
                        {
                                // getNewNameForFile will tell us if the file needs to be renamed or not
                                newName = getNewNameForFile(Path.GetFileName(fileToRename));

                                // if no newname we skip this file
                                if (newName == "") { continue; }
                                                               
                                // let's make up the new file name, taking old path and exchanging older
                                // name for the new one
                                string newFile = Path.GetDirectoryName( fileToRename )  + @"" + newName;

                                // here the file moving, Working with file system means
                                // always try/catching
                                try
                                {

                                        logToForm("[" + Path.GetFileName(fileToRename) + "] : " + newName);

                                        File.Move(fileToRename, newFile);                                      
                                        renamingCounter++;
                                }
                                catch (Exception ex)
                                {
                                        // lets log the error and carry on
                                        logToForm("* * Error trying to rename file : [err:"+ex.Message+"] " + fileToRename + " to : n* * " + newFile );
                                }
                        }

                        // Report to the log, alerts are annoying :P
                        logToForm( "- - - - - - - - - - - - - - - - - - - - - " );
                        logToForm(renamingCounter + " Files renamed");
                }

                // Here we regex the file name
                //   taking into account the renaming criteria
                //   we get rid of (...) [...] things
                //   as for years
                //   and annoying characters  
                private string getNewNameForFile(string file)
                {
                        // we make sure to work with the file name only, not touching the extension
                        string extension = Path.GetExtension(file);
                        string res = file.Trim( extension.ToCharArray() );

                        // from now on, res (short from result) wil be the string
                        // we will work with, doing all the replacing              

                        // is there any ugly string to remove from the files ?
                        if (tbStringsToRemove.Text.Trim() != "")
                        {
                                res = Regex.Replace( res ,"(" + tbStringsToRemove.Text.Trim() + ")" , "" , RegexOptions.IgnoreCase );
                        }

                        // is there chars that are meant to be spaces ?
                        // as in :  the_lord_of_the_rings ? lets replace them by spaces
                        if ( tbReplaceWithSpace.Text.Trim() != "" && cbReplaceBySpace.Checked )
                        {
                                string regx = string.Join("|",
                                        tbReplaceWithSpace.Text.Replace(" ", "").ToCharArray()).Trim('|')
        + "){1,}";
                                regx = Regex.Replace(regx, @"(|?)([wd])(|?)", "$1$2$3");
                                res = Regex.Replace(res, "(" + regx, " ", RegexOptions.IgnoreCase);

                        }

                        // from here on we apply the form's selected deletion criteria
                        // note that before applying any of them we check if the
                        // option is checked in the form

                        // if there is a list of disturbing chars to be removed we make up
                        // our regular expression for that
                        if (cbCharRemove.Checked && tbCharactersToRemove.Text.Trim() != "" )
                        {
                                string regex = string.Join( "|",
                                        tbCharactersToRemove.Text.Replace(" ","").ToCharArray() ).Trim( '|' )
                                        +  "){1,}";
                                regex = Regex.Replace(regex,@"(|?)([wd])(|?)", "$1$2$3");
                                res = Regex.Replace(res, "(" + regex, "", RegexOptions.IgnoreCase);
                        }

                        // here is the inbetween brackets [...] deletion regex
                        if (cbDeleteCor.Checked)
                        {
                                 res = Regex.Replace(res, @"[(.|swd-])*?]", "", RegexOptions.IgnoreCase);
                        }

                        // and this one is the inbetween parenthesis [...] deletion regex
                        if (cbDeletePar.Checked)
                        {
                                 res = Regex.Replace(res, @"((.|swd-)*?)", "", RegexOptions.IgnoreCase);
                        }

                        // lets erase the year, if asked for and
                        if (cbDeleteYear.Checked)
    &nbs
p;                   {
                                res = Regex.Replace(res, @"([^d]|^)(20[01]d|19[89][0-9])([^d]|$)", "");
                        }

                        res += extension;

                        // was there any replacement done ? if yes we return the new file name
                        // if not, we just give an empty string
                        return (res==file?"":res);
                }

                // Log into the multiline tbLog Textbox
                private void logToForm(string text)
                {
                        tbLog.AppendText(text + "n");
                }

                // This one liner clears the selected folders list
                private void btClearList_Click(object sender, EventArgs e)
                {
                        lbSourceFolders.Items.Clear();
                }
        }
}

 

No comments:

Post a Comment