Convert Files with a File Watcher - Console C#

This tutorial shows how to create a C# Windows Console application that uses the System.IO.FileSystemWatcher class to raise an event when a file in a directory is created and then uses the DocumentConverter class to convert and save the file to a searchable PDF file format.

Overview  
Summary This tutorial covers how to use the DocumentConverter and System.IO.FileSystemWatcher Classes in a C# Windows Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (3 KB)
Platform Windows Console C# Application
IDE Visual Studio 2017, 2019
Development License Download LEADTOOLS

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Convert Files with a File Watcher - Console C# tutorial.

Create the Project and Add the LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you don't have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by one or the other of the following two methods (but not both). For this project, the following references are needed:

If using NuGet references, this tutorial requires the following NuGet package:

If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS21\Bin\Dotnet4\x64:

For a complete list of which Codec DLLs are required for specific formats, refer to File Format Support.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note

Adding LEADTOOLS NuGet and local references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Add the FileSystemWatcher and DocumentConverter Code

With the project created, the references added, and the license set, coding can begin.

Open Program.cs in the Solution Explorer. Add the below using statements and global variables.

C#
// Using block at the top 
using System; 
using System.IO; 
using Leadtools; 
using Leadtools.Document; 
using Leadtools.Document.Converter; 
using Leadtools.Document.Writer; 
using Leadtools.Ocr; 
C#
// Add these global variables 
static string OutputDirectory; 
static DocumentConverter docConverter; 

Add the below code inside the Main method to initialize the OcrEngine, DocumentConverter, and FileSystemWatcher.

C#
static void Main(string[] args) 
{ 
    if (args.Length != 1) 
    { 
        Console.WriteLine("Usage: Convert-Files-With-a-File-Watcher.exe <directory>"); 
        return; 
    } 
 
    SetLicense(); 
 
    using (IOcrEngine OcrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD)) 
    { 
        OcrEngine.Startup(null, null, null, @"C:\LEADTOOLS21\Bin\Common\OcrLEADRuntime"); 
 
        docConverter = new DocumentConverter(); 
        docConverter.SetOcrEngineInstance(OcrEngine, false); 
        docConverter.SetDocumentWriterInstance(new DocumentWriter()); 
 
        string watchFolder = args[0]; 
 
        OutputDirectory = Path.Combine(watchFolder, "ConvertedToPDF"); 
        if (!Directory.Exists(OutputDirectory)) 
            Directory.CreateDirectory(OutputDirectory); 
 
        Console.WriteLine($"Watching folder {watchFolder}.."); 
 
        using (FileSystemWatcher systemWatcher = new FileSystemWatcher()) 
        { 
            systemWatcher.Path = watchFolder; 
            systemWatcher.NotifyFilter = NotifyFilters.LastAccess 
                                            | NotifyFilters.LastWrite 
                                            | NotifyFilters.FileName 
                                            | NotifyFilters.DirectoryName; 
 
            systemWatcher.Filter = "*.*"; 
 
            systemWatcher.Created += SystemWatcher_Created; 
 
            systemWatcher.EnableRaisingEvents = true; 
 
            Console.WriteLine("Press 'q' to quit."); 
            while (Console.Read() != 'q') ; 
        } 
    } 
} 

Because the IOcrEngine interface implements IDisposable, make sure it is in a using statement for proper disposal.

Create a FileSystemWatcher.Create event handler and add the below code to it.

C#
static void SystemWatcher_Created(object sender, FileSystemEventArgs e) 
{ 
    string file = e.FullPath; 
    string output = Path.Combine(OutputDirectory, Path.ChangeExtension(e.Name, "pdf")); 
 
    ConvertFile(file, output); 
} 

Create the ConvertFile(string input, string output) method called in the event handler and add the below code to convert each file added to the specified file directory to PDF.

C#
private static void ConvertFile(string input, string output) 
{ 
    var inputDocument = DocumentFactory.LoadFromFile(input, new LoadDocumentOptions()); 
 
    DocumentConverterJobData jobData = new DocumentConverterJobData() 
    { 
        Document = inputDocument, 
        OutputDocumentFileName = output, 
        DocumentFormat = DocumentFormat.Pdf, 
    }; 
 
    var job = docConverter.Jobs.CreateJob(jobData); 
    docConverter.Jobs.RunJob(job); 
 
    if (job.Errors.Count > 0) 
        foreach (var converterJobError in job.Errors) 
            Console.WriteLine($"Error During Conversion:{converterJobError.Error.Message}"); 
        else 
            Console.WriteLine($"Converted {input} to PDF. Save location: {output}"); 
} 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the application runs and listens for any new file added to the specified file directory. Once a file is added, the application then grabs that file and converts it to PDF and outputs the PDF to the OutputDirectory.

Wrap-up

This tutorial showed how to convert any file format supported by LEADTOOLS to PDF using a FileSystemWatcher. In addition, it showed how to use the DocumentConverter class and the IOcrEngine interface.

See Also

Help Version 21.0.2021.5.11
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.