【问题标题】:Rename a set of files using the information present in a txt file使用 txt 文件中的信息重命名一组文件
【发布时间】:2019-05-12 14:31:21
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您能否举例说明预期的输出应该是什么?
  • 我有一个包含很多文件的文件夹,例如:001.pdf、002.pdf、003.pdf 和一个 txt 文件,其中包含我在第一篇文章中输入的值。我想使用该 txt 文件中的字符串重命名 pdf 文件。 txt 文件的第一行包含 pdf 文件的名称(不带引号)。第二行将是第二个 pdf 文件的名称,依此类推。
  • 那么对于"2222" "_" "Z1" "001" "E" "07",您期望的文件名是什么?
  • 是的。这将是第一个不带引号的 pdf (001) 的名称。 "2222" "_" "C1" "002" "F" "08" 将是第二个的名称,依此类推。
  • 你怎么知道要重命名什么文件?还是没关系?

标签: c# list rename


【解决方案1】:

您可以使用以下代码作为起点,并在必要时使其更复杂。我有 cmets 可以帮助跟进。请记住包括“使用 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++;
            }
        }
    }
}

【讨论】:

  • 谢谢 Cardi DeMonaco Jr。让我试试吧。
  • 它重命名这些文件,但名称错误。第一个 pdf 的名称是:_.pdf。第二个是:222.pdf 第三个是:Z1.pdf
  • 那么第一个 PDF 的名称应该是什么?
  • 目前文本文件中的名称与目录中的 PDF 没有关联。您需要在某处实现某种排序。不保证 Directory.GetFiles(string) 中文件的顺序。请参阅documentation 了解更多信息。
  • 第一个必须是:2222_Z1001E07.pdf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 2014-02-13
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多