Rename files from a txt list

Asked

Viewed 56 times

1

I am trying to develop a small program that allows me to rename a set of files (pdf type existing in a given directory and whose name is sequential: 001.pdf, 002.pdf, 003.pdf, etc.), using existing information in a txt file.

The information in the txt file is as follows:

"2500" "_" "W1" "001" "E" "04"

"2500" "_" "W1" "002" "E" "05"

"2500" "_" "W1" "003" "E" "04"

The goal is for pdf files to be renamed based on txt text lines, not using quotes. For example the 001.pdf file would be 2500_W1001E04.pdf and so on.

The code that I already have and which I think could allow us to go further is as follows::

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace _utilitarios
{
    public partial class FormRenomear : Form
    {
        public FormRenomear()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Diretorio que contem os ficheiros pdf e o txt de referência para a renomeação dos ficheiros.
            string directory = @"C:\Users\arquivo1\arquivo2\";

            //Ficheiro do tipo txt que contém a lista para renomear os ficheiros.
            string filenames = File.ReadAllText(directory + "lista.txt");

            //Remove as aspas e separa por espaços.
            string[] listFilenames = filenames.Replace("\"", "").Split('\t');

            int i = 0; //Usado para aceder á lista de ficheiros.
            foreach (string file in Directory.GetFiles(directory))
            {
                //Ignorar o ficheiro txt.
                if (!file.EndsWith(".txt"))
                {
                    //Renomear o ficheiro.
                    File.Move(file, directory + listFilenames[i] + ".pdf");
                    i++;
                }
            }
        }
    }
}
  • And what exactly is your problem? What is not working in your code?

  • The result I get after running the code is not what I want. In the 3 examples, what I get is the renamed files: _.pdf ; 2500.pdf ; W1.pdf

1 answer

1


The problem is that the TAB.

By doing the Split('\t') the text is being divided by TAB instead of removing the TAB and then divide by line break.

The solution may replace the line:

string[] listFilenames = filenames.Replace("\"", "").Split('\t');

For this:

string[] listFilenames = filenames.Replace("\"", string.Empty).Replace("\t", string.Empty).Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
  • Excellent! That’s right! Thank you.

Browser other questions tagged

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