Search code examples
c#fileforeachdirectory

Loop directory to return multiple PDF Files


I need to fill in pdf form fields using itext7. My logic is generating 1 file but i need it to generate all the PDFs placed inside the given folder, at a time. My working is as follows:

[HttpPost]
public IActionResult Create(Job newJob)
{
    string path = MyServer.MapPath(@"\Files\");
    DirectoryInfo d = new DirectoryInfo(path);

    foreach (var file in d.GetFiles("*.pdf"))
    {
        if (System.IO.File.Exists(file.FullName))
        {
            var sourceFileStream = System.IO.File.OpenRead(file.FullName); 
            var outputStream = new MemoryStream();
            var pdf = new PdfDocument(new PdfReader(sourceFileStream), new PdfWriter(outputStream));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);
            if (form != null)
            {
                IDictionary<String, PdfFormField> fields = form.GetAllFormFields();
                PdfFormField toset;
                fields.TryGetValue("CustomerName", out toset);
                toset.SetValue(newJob.CustomerName);

                fields.TryGetValue("PropertyAddress", out toset);
                toset.SetValue(newJob.PropertyAddress);
                pdf.Close();
            }
            byte[] bytes = outputStream.ToArray();
            var OutputFile = File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.FullName);
            return OutputFile;
        }  
    }
    return View();
}

As you notice, after returning the first OutputFile, program is quitting and not looping through the directory for the second pdf File to generate. Can you please show me ways to loop through the directory after the first OutputFile is ready.

Thanks in advance


Solution

  • Your return OutputFile; statement ends the current method, returning the result to the caller.

    When doing so, it will also end foreach it is in, and the if, and everything.

    What you coded here is returning the first file you created, or View() if you did not create any file at all.

    What I really find interesting is that this code sample even compiles, because your method returns an IActionResult interface, which a Fileobject dont implement.

    The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

    So: do not return the created File, create a real ActionResult instead.