首页 > 解决方案 > 使用 txt 文件中的信息重命名一组文件

问题描述

我对如何根据 txt 文件中存在的信息来解决重命名一组 pdf 文件的问题有一些疑问。例如,假设在 txt 文件中,以下数据由制表符分隔:

"2222" "_" "Z1" "001" "E" "07"

"2222" "_" "C1" "002" "F" "08"

"2222" "_" "D1" "003" "F" "09"

给定文件夹中的 pdf 文件数始终对应于 txt 文件中的行数。如何使用 txt 文件中的此信息更改 * pdf 文件的名称,该文件位于 pdf 所在的同一文件夹中,不带引号?

标签: c#listrename

解决方案


您可以使用以下代码作为起点,并在必要时使其更复杂。我有意见可以帮助跟进。请记住包括“使用 System.IO;”。

class Program
{
    static void Main(string[] args)
    {
        string directory = @"E:\TempFiles\"; //Name of directory containing text files and PDFs

        //Get text file with names for PDFs...
        string filenames = File.ReadAllText(directory + "names.txt");

        //Removed quotes, but can be done differently, and split by space, which may not work for all your cases, but gets going in the right direction...
        string[] listFilenames = filenames.Replace("\"", "").Split('\t');

        int i = 0; //Used to access list of filnames...
        foreach (string file in Directory.GetFiles(directory))
        {
            //Skip text file...
            if (!file.EndsWith(".txt"))
            {
                //Rename file...
                File.Move(file, directory + listFilenames[i] + ".pdf");
                i++;
            }
        }
    }
}

推荐阅读