Program to rename files

1

I am trying to develop a small program to rename batches of files (pdf, etc). Imagine that the default is "1250_F1_001A_E01-001A00.pdf" and in the end it would get "1250_F1001A00.pdf", it kept the first 7 and the last 6 of any file. What's in the middle would be eliminated.

The problem is in fileName.LastIndexOf(3, 3)); gives error constantly.

The code I am trying to produce is as follows:

namespace RenomeiaPdfs
{
    class Program
    {
        static void Main(string[] args)
        {
            const string DIRECTORY_PATH = @"C:\Users\...\RENOMEIA";
            if (Directory.Exists(DIRECTORY_PATH))
            {
                string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
                foreach (string filePath in filePathList)
                {
                    if (File.Exists(filePath))
                    {
                        // Get the file name
                        string fileName = Path.GetFileName(filePath);
                        // Get the file extension
                        string fileExtension = Path.GetExtension(filePath);

                        // Get the file name without the midle part
                        string fileTitle = fileName.Substring(0, fileName.LastIndexOf(3, 3));
                        File.Move(filePath, DIRECTORY_PATH + @"\" + fileTitle + fileExtension);
                    }
                }
            }
        }
    }
}
    
asked by anonymous 25.07.2018 / 17:35

3 answers

1

Complementing the response from John , you should treat cases where the name can ("File already exists").

As a suggestion you can create a list with the new names and always when changing, check if the name of the new file is in the list, if it is, you will not be able to use it again. You can use the windows default for these cases: file (1) .pdf, file (2) .pdf etc.

obs : item.Path is your filePath

    //Lista que não aceita valores repetidos
            HashSet<string> novosNomes = new HashSet<string>();

            //Iterando pelos arquivos
            foreach (var item in files)
            {
                if (File.Exists(item.Path))
                {
                    //Nome do arquivo
                    var fileName = Path.GetFileNameWithoutExtension(item.Path);
                    //Extensão do arquivo
                    var fileExtension = Path.GetExtension(item.Path);
                    //Diretorio do arquivo
                    var path = Path.GetDirectoryName(item.Path);

                    string fileTitle = $"{fileName.Substring(0, 7)}{fileName.Substring(fileName.Length - 6, 6)}";

                    //Se o nome não for duplicado
                    if (novosNomes.Add($"{fileTitle}{fileExtension}"))
                    {
                        //Append do novo nome ao diretorio
                        var newPath = Path.Combine(path, $"{fileTitle}{fileExtension}");
                        File.Move(item.Path, newPath);
                    }
                    //Se o nome já existir na HashList
                    else
                    {
                        var novoNome = "";
                        //Variável para evitar nomes repetidos
                        int i = 1;

                        do
                        {
                            i++;
                            novoNome = string.Format("{0}{1}{2}", fileTitle, $"({i})", fileExtension);
                        } while (!novosNomes.Add(novoNome));

                        //Append do novo nome ao diretorio
                        var newPath = Path.Combine(path, novoNome);
                        File.Move(item.Path, newPath);

                    }
                }
            }
    
26.07.2018 / 14:59
0

I think this will solve your problem:

string fileTitle = $"{fileName.Substring(0, 7)}{fileName.Substring(fileName.Length - 6, 6)}";

Maybe it will also be better to validate if string is large enough to get this information:

if (fileName.Length >= 7)
    // ...
    
25.07.2018 / 17:46
0

Thank you all. I've already found the solution. The difficulty was in understanding Substring.

string fileTitle = $"{fileName.Substring(0, 7)}{fileName.Substring(fileName.Length - 10, 10)}";
    
26.07.2018 / 19:18