Convert Files with a File Watcher - C# .NET Core

This tutorial shows how to use the System.IO.FileSystemWatcher class to raise an event when a file in a directory is created and use 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 to convert files to searchable PDF in a C# .NET Core Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (2 KB)
Platform C# .NET Core Console Application
IDE Visual Studio 2017, 2019
Development License Download LEADTOOLS
Try it in another language

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 - C# .NET Core tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not 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 via NuGet packages.

This tutorial requires the following NuGet package:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

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 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.

In the Solution Explorer, open Program.cs. Add the following statements to the using block at the top of Program.cs.

C#
using System; 
using System.IO; 
using Leadtools; 
using Leadtools.Document; 
using Leadtools.Document.Converter; 
using Leadtools.Document.Writer; 
using Leadtools.Ocr; 

Add the below global variables to the Program class.

C#
static string OutputDirectory; 
static DocumentConverter docConverter; 

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

C#
static void Main(string[] args) 
{ 
    if (args.Length != 1) 
    { 
        Console.WriteLine("Usage: Convert-Files-With-a-File-Watcher.exe <directory>"); 
        return; 
    } 
 
    if (!SetLicense()) 
        Console.WriteLine("Error setting license"); 
    else 
        Console.WriteLine("License file set successfully"); 
 
    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') ; 
        } 
    } 
} 

Note

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

Create a new method named ConvertFile(string input, string output). This method will be called inside the FileSystemWatcher.Create event handler. Add the below code in the new method to convert the new file in 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}"); 
} 

Create the FileSystemWatcher.Create event handler. Hook this event handler inside the Main() method as shown above. Add the below code to the event handler to gather the input file path, create the output file path and call the ConvertFile() method created above.

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); 
} 

Run the Project

The directory in which to add the File Watcher to, will need to be designated inside the Application arguments. To add the directory, select Project -> Properties, and navigate to the Debug tab.

Once you have designated the directory to add the File Watcher to, run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the console appears and the application 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 a searchable PDF.

Wrap-up

This tutorial showed how to convert any file format supported by LEADTOOLS to PDF using the FileSystemWatcher and DocumentConverter classes.

See Also

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