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

This tutorial shows how to use 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# .NET 6 Console application.
Completion Time 20 minutes
Visual Studio Project Download tutorial project (1 KB)
Platform C# .NET 6 Console Application
IDE Visual Studio 2022
Runtime Target .NET 6 or Higher
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 this 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>\LEADTOOLS23\Bin\net:

For a complete list of which DLL files are required for your application, refer to Files to be Included in 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:

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 Leadtools; 
using Leadtools.Document; 
using Leadtools.Document.Converter; 
using Leadtools.Document.Writer; 
using Leadtools.Ocr; 
C#
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) 
{ 
   try 
   { 
      InitLEAD(); 
 
      string watchFolder = @"PLACE DIRECTORY TO WATCH HERE"; 
 
      using IOcrEngine OcrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD); 
      OcrEngine.Startup(null, null, null, @"C:\LEADTOOLS23\Bin\Common\OcrLEADRuntime"); 
 
      docConverter = new DocumentConverter(); 
      docConverter.SetOcrEngineInstance(OcrEngine, false); 
      docConverter.SetDocumentWriterInstance(new DocumentWriter()); 
 
      OutputDirectory = Path.Combine(watchFolder, "ConvertedToPDF"); 
      if (!Directory.Exists(OutputDirectory)) 
         Directory.CreateDirectory(OutputDirectory); 
 
      Console.WriteLine($"Watching folder {watchFolder}.."); 
 
      using FileSystemWatcher systemWatcher = new(); 
      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.ReadKey().KeyChar != 'q') ; 
   } 
   catch (Exception ex) 
   { 
      Console.WriteLine(ex.ToString()); 
   } 
} 

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 23.0.2024.5.22
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.