Rename files from a txt list

1

I'm trying to develop a small program that allows me to rename a set of files (type pdf 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 of the following genre:

  

"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 the text lines of the txt, not using the quotation marks. For example the file 001.pdf would be 2500_W1001E04.pdf and so on.

The code that I already have and that I think may allow you to go further is the following:

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++;
                }
            }
        }
    }
}
    
asked by anonymous 12.12.2018 / 15:21

1 answer

1

The problem is that% w / o% are not being removed.

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

The solution may be to 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);
    
12.12.2018 / 16:34