How to merge files order by filename

时间:2019-05-31 11:25:24

标签: c#

I want to create a new pdf file using iTextSharp. All my code is working but the new file doesn't are ordered by page number.

Could you kindly let me know how to modify the following code to create new pdf file ordered by file name (page number)

foreach (var file in Directory.GetFiles(path))
{
    reader = new PdfReader(file);

    for (int i = 0; i < reader.NumberOfPages; i++)
    {
        page = pdf.GetImportedPage(reader, i + 1);
        pdf.AddPage(page);
    }

    pdf.FreeReader(reader); reader.Close();
}

Folder contains 102 files. File name is Page_1, Page_2, Page_3 ...

I expected the output with pages ordered

Thank you very much in advance

1 个答案:

答案 0 :(得分:1)

Since you need to order numerically (i.e. Page_15 comes before Page_2 if you do it alphabetically), you need to extract that from the filename, for example:

// Needs some work but you get the idea
private int GetNumberFromFilename(string filename)
{
    var baseName = Path.GetFileName(filename);
    var parts = filename.Split('_','.');
    if(int.TryParse(parts[1], out var number))
    {
        return number;
    }
    return 0;
}

Now you can get your ordered files like this:

var files = Directory.GetFiles(path)
    .Where(f => Path.GetFileName(f).StartsWith("Page_")) //filter out non matching files
    .OrderBy(GetNumberFromFilename);