Click here to Skip to main content
15,669,524 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am retrieving the list of all .pdf files in a directory and I have a function to get the number of pages for one pdf.

//List of all PDF files
string[] filePaths = Directory.GetFiles(cboSource.Text, "*.pdf", SearchOption.AllDirectories);
MessageBox.Show(String.Join(Environment.NewLine, filePaths));
//Get the number of pages in a PDF file
public int GetNumberOfPdfPages(string fileName)
    using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
    	Regex regex = new Regex(@"/Type\s*/Page[^s]");
    	MatchCollection matches = regex.Matches(sr.ReadToEnd());
    	return matches.Count;

Please ignore the MessageBox as I have just used it to see whether the values are correct.

Now, I want to get the name/path of that one PDF that has the least number of pages in the total collection in
string[] filePaths

Please help.


What I have tried:

I have shown all I that I have done in my question. I have not tried anything apart from it as I am unsure of what and how to proceed
Updated 11-Apr-19 1:26am

1 solution

First of all: Your method for counting pages is not reliable.
e.g. it gave me 0 for a PDF file actually containing over 1000 pages.

If you once have a reliable page count method
you must collect filename and page count by using a model like this:
public class PdfFileInfo
    public string Filename { get; set; }
    public int PageCount { get; set; }

private void GetPdfFiles(string folder)
	var pdfFileInfos = new List<PdfFileInfo>();
	var filePaths = Directory.GetFiles(folder, "*.pdf", SearchOption.AllDirectories);

	foreach (var filePath in filePaths)
		pdfFileInfos.Add(new PdfFileInfo
			Filename = filePath,
			PageCount = GetNumberOfPdfPages(filePath)

	pdfFileInfos = pdfFileInfos.OrderBy(x => x.PageCount).ToList();

	if (pdfFileInfos.Count > 1)
		var result = pdfFileInfos[0];

		MessageBox.Show($"{result.Filename} has {result.PageCount} pages.");
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900