Program to rename files

Asked

Viewed 162 times

1

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

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

The code I’m 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);
                    }
                }
            }
        }
    }
}

3 answers

1

Complementing the response of John, you should treat cases where the name can repeat after the change (Error "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);

                    }
                }
            }
  • Thank you Joabe Alexandre. There are never repeated filenames. The name patterns are always these: 2000_F1_001_008G_E01-006G00.pdf / 2000_F1_001_008G_E01-007G00.pdf, etc and should give rise to the names: 2000_F1006G00.pdf/ 2000_F1007G00.pdf

  • I changed the code snippet to get the name without the extension (var filename = Path.Getfilenamewithoutextension(item.Path)), since with the extension it gave me a repeat error. You’ve tested that too?

  • The problem is in string fileTitle = $"{filename.Substring(0, 27)}{filename.Substring(filename.Length - 8, 10)}"; If you do not remove the correct characters, then you can create files with the same name.

  • In this excerpt, the first subtring is getting the name of the complete file (in the question the 7 first digits are asked) and at the end is getting a string beyond the size of the text. It is not clear what you are seeking.

  • string fileTitle = $"{filename.Substring(0, 7)}{filename.Substring(filename.Length - 6, 7)}"; The problem is here. It does not remove the correct characters.

0

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

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

0

I think this will solve your problem:

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

Perhaps it would also be better to validate if the string is large enough to obtain this information:

if (fileName.Length >= 7)
    // ...
  • Thank you! If I have several file types in the same folder, System.IO.Ioexception error appears: 'Unable to create a file when that file already exists.

  • But do you want to overwrite the existing file? Or simply skip to the next one?

  • It was intended to rename all files (existing in a given dir) with this pattern and characters, in order to reduce the name, but always maintaining the extension. If they are all the same type, no problem. If they are of different types, this error arises. I haven’t figured it out yet. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.