---
title: "Sample code in C# for pattern redaction and highlighting | Nutrient DCS"
canonical_url: "https://www.nutrient.io/guides/document-converter/document-converter-services/document-security/code-samples/"
md_url: "https://www.nutrient.io/guides/document-converter/document-converter-services/document-security/code-samples.md"
last_updated: "2026-06-09T10:25:14.368Z"
description: "Implement pattern redaction, highlighting, and smart redaction using C# and Nutrient Document Converter Services. Complete code examples included."
---

# Sample code in C# for pattern redaction and highlighting

This guide provides C# code examples for implementing document security features using Nutrient Document Converter Services (DCS). Document security is essential for protecting sensitive information in various scenarios:

- **Pattern redaction** - Permanently removes sensitive content like social security numbers, credit card numbers, or personal identifiable information

- **Pattern highlighting** - Visually marks sensitive content without removing it, useful for review processes

- **Smart redaction** - Uses intelligent algorithms to automatically identify and redact common sensitive data patterns

Choose the appropriate method based on your security requirements and compliance needs.

## Prerequisites

Before implementing document security features, ensure you have:

- Nutrient Document Converter Services installed and running

-.NET Framework or.NET Core development environment

- Document files for testing security operations

- Implemented `OpenService` and `CloseService` methods from the [`DocumentConverterServiceClient`](https://www.nutrient.io/guides/document-converter/document-converter-services/knowledge-base/open-and-close-documentconverterserviceclient/) sample code

- Appropriate permissions for file system access

## Pattern redaction sample code

```csharp

        /// <summary>
        /// Perform Smart Redaction on the supplied file, writing the result into the target folder
        /// </summary>
        /// <param name="ServiceURL">URL endpoint for the PDF Converter service</param>
        /// <param name="sourceFileName">Source filename</param>
        /// <param name="targetFolder">Target folder to receive the output file</param>
        static void SmartRedaction(string ServiceURL, string sourceFileName, string targetFolder)
        {
            DocumentConverterServiceClient client = null;
            try
            {
                // Create minimum OpenOptions object
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);

                // Create minimum SmartRedactionSettings
                SmartRedactionSettings smartRedactionSettings = new SmartRedactionSettings();
                smartRedactionSettings = new SmartRedactionSettings();
                // Set what needs to be redacted
                smartRedactionSettings.RedactCreditCardNumbers = BooleanEnum.True;
                smartRedactionSettings.RedactEmailAddresses = BooleanEnum.True;
                smartRedactionSettings.RedactPhoneNumbers = BooleanEnum.True;

                // Create target folder if required
                if (!Directory.Exists(targetFolder))
                {
                    Directory.CreateDirectory(targetFolder);
                }
                // ** Read the source file into a byte array.
                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(ServiceURL);

                // ** Carry out the conversion.
                byte[] result = client.SmartRedaction(sourceFile, openOptions, smartRedactionSettings);

                // ** Save the results
                if (result!= null)
                {
                    if (!Directory.Exists(targetFolder))
                    {
                        Directory.CreateDirectory(targetFolder);
                    }
                    string filename = Path.GetFileNameWithoutExtension(sourceFileName);
                    string destinationFileName = Path.GetFullPath(Path.Combine(targetFolder, filename + "-redacted.pdf"));
                    using (FileStream fs = File.Create(destinationFileName))
                    {
                        fs.Write(result, 0, result.Length);
                        fs.Close();
                    }
                    Console.WriteLine("File converted to " + destinationFileName);
                }

                else
                {
                    Console.WriteLine("Nothing returned");
                }
            }
            catch (FaultException<WebServiceFaultException> ex)
            {
                Console.WriteLine($"FaultException occurred: ExceptionType: {ex.Detail.ExceptionType.ToString()}");
                Console.WriteLine();
                Console.WriteLine($"Error Detail: {string.Join(Environment.NewLine, ex.Detail.ExceptionDetails)}");
                Console.WriteLine($"Error message: {ex.Message}");
                Console.WriteLine();
                Console.WriteLine($"Error reason: {ex.Reason}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Data.ToString());
            }
            finally
            {
                if (client!= null)
                {
                    CloseService(client);

                }
            }

        }

```

## Pattern highlighting sample code

Pattern highlighting identifies specific patterns in a document and visually highlights them without removing the underlying content. This example shows how to implement pattern highlighting using the API:

```csharp

        /// <summary>
        /// Perform pattern redaction on the supplied file, writing the result into the target folder.
        /// </summary>
        /// <param name="ServiceURL">URL endpoint for the PDF Converter service.</param>
        /// <param name="sourceFileName">Source filename.</param>
        /// <param name="targetFolder">Target folder to receive the output file.</param>
        static void PatternRedaction(string ServiceURL, string sourceFileName, string targetFolder)
        {
            DocumentConverterServiceClient client = null;
            try
            {
                // Create minimum `OpenOptions` object.
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);

                // Create minimum `PatternHighlightSettings`.
                PatternHighlightSettings patternHighlightSettings = new PatternHighlightSettings();
                // Set the highlight color.
                patternHighlightSettings.Red = 0;
                patternHighlightSettings.Green = 0;
                patternHighlightSettings.Blue = 255;
                patternHighlightSettings.Alpha = 255;
                patternHighlightSettings.Pattern = "\"374245455400126\"";

                // Create target folder if required.
                if (!Directory.Exists(targetFolder))
                {
                    Directory.CreateDirectory(targetFolder);
                }
                // ** Read the source file into a byte array.
                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings.
                client = OpenService(ServiceURL);

                // ** Carry out the highlighting.
                byte[] result = client.PatternHighlight(sourceFile, openOptions, patternHighlightSettings);

                // ** Save the results.
                if (result!= null)
                {
                    if (!Directory.Exists(targetFolder))
                    {
                        Directory.CreateDirectory(targetFolder);
                    }
                    string filename = Path.GetFileNameWithoutExtension(sourceFileName);
                    string destinationFileName = Path.GetFullPath(Path.Combine(targetFolder, filename + "-highlighted.pdf"));
                    using (FileStream fs = File.Create(destinationFileName))
                    {
                        fs.Write(result, 0, result.Length);
                        fs.Close();
                    }
                    Console.WriteLine("File converted to " + destinationFileName);
                    // Open the destination file.
                    ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName = destinationFileName;
                    psi.UseShellExecute = true;
                    Process.Start(psi);
                }
                else
                {
                    Console.WriteLine("Nothing returned");
                }
            }
            catch (FaultException<WebServiceFaultException> ex)
            {
                Console.WriteLine($"FaultException occurred: ExceptionType: {ex.Detail.ExceptionType.ToString()}");
                Console.WriteLine();
                Console.WriteLine($"Error Detail: {string.Join(Environment.NewLine, ex.Detail.ExceptionDetails)}");
                Console.WriteLine($"Error message: {ex.Message}");
                Console.WriteLine();
                Console.WriteLine($"Error reason: {ex.Reason}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Data.ToString());
            }
            finally
            {
                if (client!= null)
                {
                    CloseService(client);

                }
            }

        }

```

## Smart redaction sample code

```csharp

        /// <summary>
        /// Perform Smart Redaction on the supplied file, writing the result into the target folder
        /// </summary>
        /// <param name="ServiceURL">URL endpoint for the PDF Converter service</param>
        /// <param name="sourceFileName">Source filename</param>
        /// <param name="targetFolder">Target folder to receive the output file</param>
        static void SmartRedaction(string ServiceURL, string sourceFileName, string targetFolder)
        {
            DocumentConverterServiceClient client = null;
            try
            {
                // Create minimum OpenOptions object
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);

                // Create minimum SmartRedactionSettings
                SmartRedactionSettings smartRedactionSettings = new SmartRedactionSettings();
                smartRedactionSettings = new SmartRedactionSettings();
                // Set what needs to be redacted
                smartRedactionSettings.RedactCreditCardNumbers = BooleanEnum.True;
                smartRedactionSettings.RedactEmailAddresses = BooleanEnum.True;
                smartRedactionSettings.RedactPhoneNumbers = BooleanEnum.True;

                // Create target folder if required
                if (!Directory.Exists(targetFolder))
                {
                    Directory.CreateDirectory(targetFolder);
                }
                // ** Read the source file into a byte array.
                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(ServiceURL);

                // ** Carry out the conversion.
                byte[] result = client.SmartRedaction(sourceFile, openOptions, smartRedactionSettings);

                // ** Save the results
                if (result!= null)
                {
                    if (!Directory.Exists(targetFolder))
                    {
                        Directory.CreateDirectory(targetFolder);
                    }
                    string filename = Path.GetFileNameWithoutExtension(sourceFileName);
                    string destinationFileName = Path.GetFullPath(Path.Combine(targetFolder, filename + "-redacted.pdf"));
                    using (FileStream fs = File.Create(destinationFileName))
                    {
                        fs.Write(result, 0, result.Length);
                        fs.Close();
                    }
                    Console.WriteLine("File converted to " + destinationFileName);
                }

                else
                {
                    Console.WriteLine("Nothing returned");
                }
            }
            catch (FaultException<WebServiceFaultException> ex)
            {
                Console.WriteLine($"FaultException occurred: ExceptionType: {ex.Detail.ExceptionType.ToString()}");
                Console.WriteLine();
                Console.WriteLine($"Error Detail: {string.Join(Environment.NewLine, ex.Detail.ExceptionDetails)}");
                Console.WriteLine($"Error message: {ex.Message}");
                Console.WriteLine();
                Console.WriteLine($"Error reason: {ex.Reason}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Data.ToString());
            }
            finally
            {
                if (client!= null)
                {
                    CloseService(client);

                }
            }

        }

```

## Troubleshooting

**Pattern matching error: Pattern not found**

- Verify that the pattern exists in the document

- Check pattern syntax and escape special characters

- Ensure the pattern format matches the document content structure

**Security operation error: Permission denied**

- Verify that the application has read access to source documents

- Check that the output directory has write permissions

- Ensure documents aren’t password-protected or locked by other applications

**Service connection error: Cannot connect to DCS**

- Ensure Nutrient Document Converter Services is running and accessible

- Verify the service URL in your code matches your DCS installation

- Check that no firewall is blocking the connection

**Performance issues: Slow processing**

- Consider processing documents in batches for large volumes

- Optimize pattern complexity to reduce processing time

- Monitor memory usage for large documents

## What’s next

Now that you understand document security implementation with C#, explore these related capabilities:

- **Python implementation** - Compare with [pattern redaction using Python](https://www.nutrient.io/guides/document-converter/document-converter-services/document-security/pattern-redaction-using-python.md) for cross-language insights

- **Complete C# guide** - Review the [document security with C#](https://www.nutrient.io/guides/document-converter/document-converter-services/document-security/csharp.md) guide for more features
---

## Related pages

- [Secure PDF API](/guides/document-converter/document-converter-services/document-security.md)
- [Secure PDF and MS Office documents with Java](/guides/document-converter/document-converter-services/document-security/java.md)
- [Secure and protect PDFs and Office documents in C#](/guides/document-converter/document-converter-services/document-security/csharp.md)
- [Secure your PDFs and Office files easily with .NET](/guides/document-converter/document-converter-services/document-security/dotnet-core.md)
- [WSDL URL.](/guides/document-converter/document-converter-services/document-security/pattern-redaction-using-python.md)
- [WSDL URL.](/guides/document-converter/document-converter-services/document-security/pattern-highlighting-using-python.md)
- [Secure PDF and Office documents with JavaScript](/guides/document-converter/document-converter-services/document-security/javascript.md)
- [Pattern redaction and highlighting with C#](/guides/document-converter/document-converter-services/document-security/pattern-redaction-and-highlighting.md)
- [Password protection for PDF documents in PHP](/guides/document-converter/document-converter-services/document-security/php.md)
- [Smart document redaction with C#](/guides/document-converter/document-converter-services/document-security/smart-redaction.md)

