Zum Fußzeileninhalt springen
.NET HILFE

C# Directory.GetFiles (Wie es funktioniert: Ein Leitfaden für Entwickler)

C# out parameter. By pairing this functionality with IronPDF, developers can automate PDF workflows at scale. For example, you can use Directory.GetFiles to locate all PDF files in a folder, then process them in bulk using IronPDF for tasks such as merging, adding annotations, or generating reports. This combination allows for streamlined operations, especially when dealing with many files in the file system.

What is IronPDF?

IronPDF is a robust .NET library that provides developers with tools to work seamlessly with PDF files. With IronPDF, you can create, edit, merge, split, and manipulate PDFs using straightforward, intuitive methods. It includes powerful features such as HTML-to-PDF conversion, advanced styling, and metadata handling. For .NET developers working on applications that require PDF processing, IronPDF is an invaluable tool that streamlines workflows and enhances productivity.

Getting Started

Installing IronPDF

NuGet Package Installation

To begin, add IronPDF to your project via NuGet:

  1. Open your project in Visual Studio.
  2. Go to the Tools menu and select NuGet Package Manager > Manage NuGet Packages for Solution.
  3. Search for IronPDF in the NuGet package manager.

C# Directory.GetFiles (How It Works: A Guide for Developers): Figure 1

  1. Install the latest version of IronPDF.

Alternatively, use the NuGet Package Manager Console:

Install-Package IronPdf

Basics of Directory.GetFiles in C#

The Directory.GetFiles method is part of the System.IO namespace and is used to retrieve file names from a file system. This method, a public static string member of the Directory class, simplifies accessing file paths. For instance:

string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
Dim pdfFiles() As String = Directory.GetFiles("C:\Documents\PDFs", "*.pdf")
$vbLabelText   $csharpLabel

This snippet retrieves all PDF files within the current directory. By combining this method with IronPDF, you can create automated solutions for processing multiple files at once. You can also apply a specified search pattern, defined as a string pattern, to filter files based on their extensions or names.

You can further refine your file retrieval logic by specifying search options, such as including search subdirectories:

string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf", SearchOption.AllDirectories);
string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf", SearchOption.AllDirectories);
Dim pdfFiles() As String = Directory.GetFiles("C:\Documents\PDFs", "*.pdf", SearchOption.AllDirectories)
$vbLabelText   $csharpLabel

This ensures that files in nested folders are also included, retrieving each file's absolute path and making the approach versatile for various scenarios.

Practical Use Cases

Fetching and Processing PDF Files from a Directory

Example: Loading All PDF Files for Processing

Using Directory.GetFiles, you can iterate over all PDF files in a directory and process them with IronPDF:

string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
foreach (string file in pdfFiles)
{
    // Load the PDF with IronPDF
    var pdf = PdfDocument.FromFile(file);
    Console.WriteLine($"Processing file: {Path.GetFileName(file)}");
}
string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
foreach (string file in pdfFiles)
{
    // Load the PDF with IronPDF
    var pdf = PdfDocument.FromFile(file);
    Console.WriteLine($"Processing file: {Path.GetFileName(file)}");
}
Dim pdfFiles() As String = Directory.GetFiles("C:\Documents\PDFs", "*.pdf")
For Each file As String In pdfFiles
	' Load the PDF with IronPDF
	Dim pdf = PdfDocument.FromFile(file)
	Console.WriteLine($"Processing file: {Path.GetFileName(file)}")
Next file
$vbLabelText   $csharpLabel

C# Directory.GetFiles (How It Works: A Guide for Developers): Figure 2

This example demonstrates how to load multiple PDFs from a directory for processing. Once loaded, you can perform a variety of operations, such as extracting text, adding annotations, or generating new PDFs based on their content.

Filtering Files Using Search Patterns

Example: Selecting PDFs by Name or Date

You can combine Directory.GetFiles with LINQ to filter files based on criteria such as creation or modification date:

string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
var recentFiles = pdfFiles.Where(file => File.GetLastWriteTime(file) > DateTime.Now.AddDays(-7));
foreach (string file in recentFiles)
{
    Console.WriteLine($"Recent file: {Path.GetFileName(file)}");
}
string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
var recentFiles = pdfFiles.Where(file => File.GetLastWriteTime(file) > DateTime.Now.AddDays(-7));
foreach (string file in recentFiles)
{
    Console.WriteLine($"Recent file: {Path.GetFileName(file)}");
}
Dim pdfFiles() As String = Directory.GetFiles("C:\Documents\PDFs", "*.pdf")
Dim recentFiles = pdfFiles.Where(Function(file) File.GetLastWriteTime(file) > DateTime.Now.AddDays(-7))
For Each file As String In recentFiles
	Console.WriteLine($"Recent file: {Path.GetFileName(file)}")
Next file
$vbLabelText   $csharpLabel

C# Directory.GetFiles (How It Works: A Guide for Developers): Figure 3

This approach ensures that only relevant files are processed, saving time and computational resources. For example, you might use this method to process only the latest invoices or reports generated within the last week.

Batch Operations with IronPDF and Directory.GetFiles

Example: Appending Multiple PDFs

You can append multiple PDFs from a directory into a single file:

string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
var pdfAppend = new PdfDocument(200, 200);
foreach (string file in pdfFiles)
{
    var pdf = PdfDocument.FromFile(file);
    pdfAppend.AppendPdf(pdf);
}
pdfAppend.SaveAs("LargePdf.pdf");
Console.WriteLine("PDFs Appended successfully!");
string[] pdfFiles = Directory.GetFiles("C:\\Documents\\PDFs", "*.pdf");
var pdfAppend = new PdfDocument(200, 200);
foreach (string file in pdfFiles)
{
    var pdf = PdfDocument.FromFile(file);
    pdfAppend.AppendPdf(pdf);
}
pdfAppend.SaveAs("LargePdf.pdf");
Console.WriteLine("PDFs Appended successfully!");
Dim pdfFiles() As String = Directory.GetFiles("C:\Documents\PDFs", "*.pdf")
Dim pdfAppend = New PdfDocument(200, 200)
For Each file As String In pdfFiles
	Dim pdf = PdfDocument.FromFile(file)
	pdfAppend.AppendPdf(pdf)
Next file
pdfAppend.SaveAs("LargePdf.pdf")
Console.WriteLine("PDFs Appended successfully!")
$vbLabelText   $csharpLabel

C# Directory.GetFiles (How It Works: A Guide for Developers): Figure 4

This approach is particularly useful for creating consolidated reports, archiving multiple documents, or preparing presentations. By automating this process, you can handle large collections of files effortlessly.

Step-by-Step Implementation

Setting Up the Project

Code Snippet: Initializing IronPDF and Working with PDF Files

The following code demonstrates how IronPDF can be used alongside Directory.GetFiles to load and work with PDF documents.

using IronPdf;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Retrieve all PDF file paths from the specified directory
        string[] pdfFiles = Directory.GetFiles("C:\\Users\\kyess\\Documents\\PDFs", "*.pdf");

        // Initialize a PdfDocument
        var pdfAppend = new PdfDocument(200, 200);

        // Create a text annotation to add to each PDF
        TextAnnotation annotation = new TextAnnotation(0)
        {
            Contents = "Processed by IronPDF",
            X = 50,
            Y = 50,
        };

        // Iterate over each file path, load, annotate, and save
        foreach (string file in pdfFiles)
        {
            var pdf = PdfDocument.FromFile(file);
            pdf.Annotations.Add(annotation);
            pdf.SaveAs(file);
        }
    }
}
using IronPdf;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Retrieve all PDF file paths from the specified directory
        string[] pdfFiles = Directory.GetFiles("C:\\Users\\kyess\\Documents\\PDFs", "*.pdf");

        // Initialize a PdfDocument
        var pdfAppend = new PdfDocument(200, 200);

        // Create a text annotation to add to each PDF
        TextAnnotation annotation = new TextAnnotation(0)
        {
            Contents = "Processed by IronPDF",
            X = 50,
            Y = 50,
        };

        // Iterate over each file path, load, annotate, and save
        foreach (string file in pdfFiles)
        {
            var pdf = PdfDocument.FromFile(file);
            pdf.Annotations.Add(annotation);
            pdf.SaveAs(file);
        }
    }
}
Imports IronPdf
Imports System
Imports System.IO

Friend Class Program
	Shared Sub Main()
		' Retrieve all PDF file paths from the specified directory
		Dim pdfFiles() As String = Directory.GetFiles("C:\Users\kyess\Documents\PDFs", "*.pdf")

		' Initialize a PdfDocument
		Dim pdfAppend = New PdfDocument(200, 200)

		' Create a text annotation to add to each PDF
		Dim annotation As New TextAnnotation(0) With {
			.Contents = "Processed by IronPDF",
			.X = 50,
			.Y = 50
		}

		' Iterate over each file path, load, annotate, and save
		For Each file As String In pdfFiles
			Dim pdf = PdfDocument.FromFile(file)
			pdf.Annotations.Add(annotation)
			pdf.SaveAs(file)
		Next file
	End Sub
End Class
$vbLabelText   $csharpLabel

Console Output

C# Directory.GetFiles (How It Works: A Guide for Developers): Figure 5

Explanation

This code demonstrates how to add a text annotation to all PDF files in a specified directory using IronPDF in C#. The program begins by retrieving all PDF file paths from the folder provided using the Directory.GetFiles method, which relies on a string path to specify the directory and supports filtering by file extension, returning an array of string filenames containing the paths of all PDF files with the ".pdf" extension.

Next, the code initializes a PdfDocument object (pdfAppend) with dimensions 200x200, although this specific instance isn't used directly in the loop. It then creates a TextAnnotation with the text "Processed by IronPDF" positioned at coordinates (50, 50). This annotation will be added to each PDF file.

In the foreach loop, the program iterates through each file path in the pdfFiles array. For each file, it loads the PDF using PdfDocument.FromFile(file), adds the previously created annotation to the PDF's Annotations collection, and then saves the updated PDF back to its absolute path using pdf.SaveAs(file).

This process ensures that every PDF in the specified directory receives the same annotation and is saved with the annotation included.

Performance Tips and Best Practices

Optimizing File Retrieval with Directory.GetFiles

Use asynchronous methods like Directory.EnumerateFiles for better performance with large directories.

Managing Large Numbers of Files Efficiently

Process files in smaller batches to reduce memory consumption:

foreach (var batch in pdfFiles.Batch(10))
{
    foreach (string file in batch)
    {
        var pdf = PdfDocument.FromFile(file);
        // Process PDF
    }
}
foreach (var batch in pdfFiles.Batch(10))
{
    foreach (string file in batch)
    {
        var pdf = PdfDocument.FromFile(file);
        // Process PDF
    }
}
For Each batch In pdfFiles.Batch(10)
	For Each file As String In batch
		Dim pdf = PdfDocument.FromFile(file)
		' Process PDF
	Next file
Next batch
$vbLabelText   $csharpLabel

Error Handling in File Processing and PDF Generation

Wrap file processing in a try-catch block to handle exceptions:

try
{
    var pdf = PdfDocument.FromFile(file);
    // Process PDF
}
catch (Exception ex)
{
    Console.WriteLine($"Error processing {file}: {ex.Message}");
}
try
{
    var pdf = PdfDocument.FromFile(file);
    // Process PDF
}
catch (Exception ex)
{
    Console.WriteLine($"Error processing {file}: {ex.Message}");
}
Try
	Dim pdf = PdfDocument.FromFile(file)
	' Process PDF
Catch ex As Exception
	Console.WriteLine($"Error processing {file}: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

Conclusion

Combining the power of Directory.GetFiles with IronPDF allows developers to efficiently manage and process PDF files at scale. With this approach, tasks such as batch processing, merging, filtering, and transforming PDFs become seamless, significantly reducing manual effort and improving productivity. By leveraging the advanced capabilities of IronPDF, including adding headers, metadata, and styling, developers can create high-quality, professional PDF documents tailored to their requirements.

Throughout this guide, we’ve explored how to use Directory.GetFiles to retrieve and manipulate PDFs with IronPDF. From setting up a project to implementing practical use cases, we covered essential techniques that can be applied to real-world scenarios. Whether you are working on automating document workflows or enhancing the functionality of your .NET applications, this combination provides a robust and scalable solution.

If you're ready to dive deeper into IronPDF and explore advanced features, consider referring to the official documentation, allowing you to test the library in your own projects.

Häufig gestellte Fragen

Wie funktioniert die Methode Directory.GetFiles in C#?

Die Methode Directory.GetFiles in C# ist Teil des Namespaces System.IO, der es Entwicklern ermöglicht, Dateipfade aus einem angegebenen Verzeichnis abzurufen. Sie unterstützt Suchmuster und Optionen zum Einbeziehen von Unterverzeichnissen, was sie effizient macht, um auf bestimmte Dateitypen oder -namen zuzugreifen.

Wie benutze ich C# zur Automatisierung der PDF-Verarbeitung?

Sie können die Verarbeitung von PDF-Dateien in C# automatisieren, indem Sie IronPDF zusammen mit der Methode Directory.GetFiles verwenden. Dadurch können Sie PDF-Dateien in einem Verzeichnis finden und Aufgaben wie das Zusammenführen, Hinzufügen von Anmerkungen oder das Erstellen von Berichten automatisch ausführen.

Welche Vorteile bietet die Kombination von Directory.GetFiles mit einer PDF-Bibliothek?

Die Kombination von Directory.GetFiles mit einer PDF-Bibliothek wie IronPDF ermöglicht eine automatisierte und effiziente Verwaltung von PDF-Dokumenten. Sie können PDFs massenweise abrufen und verarbeiten, Änderungen vornehmen und Dateien konsolidieren, was die Produktivität steigert und manuelle Arbeiten reduziert.

Wie füge ich mehrere PDFs zu einem einzigen Dokument in C# zusammen?

Um mehrere PDFs zu einem einzigen Dokument zusammenzuführen, verwenden Sie Directory.GetFiles, um alle PDF-Dateien in einem Verzeichnis abzurufen. Laden Sie dann jede PDF-Datei mit IronPDF und fügen Sie sie in ein einzelnes PdfDocument-Objekt ein, das als konsolidierte PDF-Datei gespeichert werden kann.

Wie kann ich Verzeichnisdateien nach Erstellungsdatum in C# filtern?

Sie können Verzeichnisdateien nach Erstellungsdatum mit LINQ und Directory.GetFiles filtern. Zum Beispiel, um Dateien auszuwählen, die in der letzten Woche erstellt wurden: var recentFiles = pdfFiles.Where(file => File.GetCreationTime(file) > DateTime.Now.AddDays(-7));

Was ist die beste Vorgehensweise zur Verarbeitung großer Dateimengen in C#?

Zur Verarbeitung großer Dateimengen verwenden Sie asynchrone Methoden wie Directory.EnumerateFiles, um die Leistung durch Reduzierung der Abrufzeit zu verbessern. Dies ist besonders nützlich, um große Verzeichnisse effizient zu handhaben.

Wie kann ich Fehler bei der Verarbeitung von PDF-Dateien in C# behandeln?

Behandeln Sie Fehler während der Verarbeitung von PDF-Dateien, indem Sie Vorgänge in einen try-catch-Block einwickeln. Dies stellt sicher, dass Ausnahmen elegant verwaltet werden, sodass die Anwendung ohne Absturz aufgrund unerwarteter Fehler weiterläuft.

Was ist ein Beispiel für die Stapelverarbeitung mit einer PDF-Bibliothek in C#?

Ein Beispiel für die Stapelverarbeitung ist die Verwendung von Directory.GetFiles, um PDFs abzurufen, und dann der Einsatz von IronPDF, um sie in großen Mengen zu zusammenzufügen oder zu annotieren. Dieser Ansatz automatisiert sich wiederholende Aufgaben und spart Zeit und Mühe.

Wie kann ich Textanmerkungen mit einer .NET-Bibliothek zu PDFs hinzufügen?

Um Textanmerkungen zu PDFs mit IronPDF hinzuzufügen, erstellen Sie ein TextAnnotation-Objekt mit festgelegtem Inhalt und Position. Laden Sie jede PDF-Datei, fügen Sie die Anmerkung zur Annotationssammlung hinzu und speichern Sie das aktualisierte Dokument.

Welche Schritte gibt es, um eine PDF-Bibliothek über NuGet in Visual Studio zu installieren?

Um eine PDF-Bibliothek über NuGet in Visual Studio zu installieren, öffnen Sie Ihr Projekt, navigieren Sie zu Tools > NuGet-Paket-Manager > NuGet-Pakete für die Lösung verwalten, suchen Sie nach IronPDF und installieren Sie es. Alternativ können Sie die NuGet-Paket-Manager-Konsole mit dem Befehl Install-Package IronPdf verwenden.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen