This C# sample signs all the files of a folder, of any type, in CAdES format: every signature is saved as a .p7m file. A single CadesSignature object signs all the files, and a second method signs them in parallel.

How it works

  • The certificate and the settings are set once; ApplyDigitalSignature(file) signs every file.
  • A file that cannot be signed is reported and the batch continues.
  • In parallel, every thread has its own signature object (a signature object is not thread-safe), while the PFX certificate is shared; the progress is counted with Interlocked.

C# code: sign a folder in CAdES format

/// <summary>
/// Signs all the files of a folder, of any type, in CAdES format. The signature of every file is saved in a .p7m file.
/// </summary>
static void SignAllFilesInCadesFormat(string sourceFolder, string destinationFolder)
{
    // A single CadesSignature object signs all the files: the certificate and the settings are set only once.
    CadesSignature cadesSignature = new CadesSignature(LibrarySerialNumber);

    cadesSignature.DigitalSignatureCertificate = LoadSigningCertificate();

    // The signed file is included in the signature (.p7m). For a separate signature file (.p7s) set:
    // cadesSignature.IsDetachedSignature = true;

    // Optionally, the signatures can be time-stamped (RFC 3161) by a Time Stamping Authority (TSA).
    // cadesSignature.TimeStamping.ServerUrl = new Uri("https://ca.signfiles.com/TSAServer.aspx");

    string[] files = Directory.GetFiles(sourceFolder);
    Console.WriteLine("Number of files that will be signed in CAdES format: " + files.Length);

    int signedFiles = 0;
    int processedFiles = 0;

    foreach (string file in files)
    {
        try
        {
            // The signed file is saved with the .p7m extension (.p7s for the detached signatures).
            File.WriteAllBytes(Path.Combine(destinationFolder, Path.GetFileName(file) + ".p7m"), cadesSignature.ApplyDigitalSignature(file));

            signedFiles++;
            Console.WriteLine("File " + Path.GetFileName(file) + " was signed in CAdES format (" + (processedFiles + 1) + " of " + files.Length + ").");
        }
        catch (Exception ex)
        {
            Console.WriteLine("File " + Path.GetFileName(file) + " was NOT signed: " + ex.Message);
        }

        processedFiles++;
    }

    Console.WriteLine("Signed CAdES files: " + signedFiles + " of " + files.Length + Environment.NewLine);
}

C# code: sign the files in parallel

/// <summary>
/// Signs all the files of a folder in CAdES format, in parallel. The signed files are saved in a sub-folder of the destination folder.
/// </summary>
static void SignAllFilesInParallel(string sourceFolder, string destinationFolder)
{
    // The certificate (a PFX file) can be shared by the threads.
    X509Certificate2 certificate = LoadSigningCertificate();

    string[] files = Directory.GetFiles(sourceFolder);
    Console.WriteLine("Number of files that will be signed in parallel in CAdES format: " + files.Length);

    int signedFiles = 0;
    int processedFiles = 0;

    ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = Math.Min(4, Environment.ProcessorCount) };

    Parallel.ForEach(
        files,
        options,

        // A signature object is not thread-safe: every worker thread has its own object, created once.
        () =>
        {
            CadesSignature threadSignature = new CadesSignature(LibrarySerialNumber);
            threadSignature.DigitalSignatureCertificate = certificate;

            return threadSignature;
        },

        (file, loopState, index, threadSignature) =>
        {
            try
            {
                File.WriteAllBytes(Path.Combine(destinationFolder, Path.GetFileName(file) + ".p7m"), threadSignature.ApplyDigitalSignature(file));
                Interlocked.Increment(ref signedFiles);
            }
            catch (Exception ex)
            {
                Console.WriteLine("File " + Path.GetFileName(file) + " was NOT signed: " + ex.Message);
            }

            // The progress is counted with Interlocked, because the files finish at the same time on different threads.
            Console.WriteLine("Processed " + Interlocked.Increment(ref processedFiles) + " of " + files.Length + ": " + Path.GetFileName(file));

            return threadSignature;
        },

        threadSignature => { });

    Console.WriteLine("Signed CAdES files (parallel): " + signedFiles + " of " + files.Length + Environment.NewLine);
}

A complete parallel batch is the project Batch Signing with Parallelism, also included in the download.

Run the full sample. The complete Visual Studio project Batch P7M P7S CAdES and PDF Signatures is included in the library download, in the folder NET Sample Projects (.NET 8, .NET 9, .NET 10 and .NET 11) and in NET Framework Sample Projects (.NET Framework 4.6.2), with the test files and a test certificate. Without a serial number the library runs in demo mode. Download the library and the samples · User manual

Frequently asked questions

Can I create detached .p7s signatures in bulk?

Yes. Set IsDetachedSignature = true and save the signatures with the .p7s extension.

Can I sign in parallel with a smart card?

Usually not: a smart card or a USB token signs one operation at a time. Parallel signing is useful with PFX certificates.