How to Delete Files On-Demand in .NET with C#

Discover how to leverage the pdfRest Delete Files API in C# to instantly remove files you’ve uploaded or generated.
Share this page

Delete pdfRest Files on Demand with C#

The pdfRest Cloud API automatically removes uploaded and generated files after the retention period associated with the account, which is 30 minutes for most plans. When a .NET application must remove those resources as soon as a workflow finishes, the pdfRest Delete Files API Tool provides an explicit /delete endpoint for permanent, on-demand cleanup.

The endpoint can delete multiple resource IDs in one call, making it suitable for workflows that create an input and several intermediate outputs. Deletion is irreversible, so the application should not treat it as a routine step that runs regardless of state. Every required result must be saved, and every operation that depends on the resource must finish, before its ID is submitted.

For example, a C# claims-processing service can upload a claim package, generate a searchable PDF, extract structured data, and copy the approved outputs into the insurer's system of record. Once those writes are verified, the service can submit the source and intermediate pdfRest resource IDs together for deletion. Centralized tracking prevents an intermediate file from being overlooked and prevents a still-active resource from being removed too early.

This example uses HttpClient and MultipartFormDataContent to delete a comma-separated list of IDs.

C# Delete Files Code Example

Set PDFREST_API_KEY in the environment, optionally set PDFREST_URL for the processing region, and replace the resource-ID placeholders. The IDs must have been created under the same API key used for the delete request.

/*
 * What this sample does:
 * - Deletes multiple resources by ids.
 * - Routed from Program.cs as: `dotnet run -- batch-delete-multipart id1 [id2] [...]`.
 *
 * Setup (environment):
 * - Copy .env.example to .env
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
 *     PDFREST_URL=https://eu-api.pdfrest.com
 *   For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 *
 * Usage:
 *   dotnet run -- batch-delete-multipart id1 id2 id3
 *
 * Output:
 * - Prints the JSON response. Validation errors (args/env) exit non-zero.
 */

namespace Samples.EndpointExamples.MultipartPayload
{
    public static class BatchDelete
    {
        public static async Task Execute(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                Console.Error.WriteLine("batch-delete-multipart requires id1 [id2] [...]");
                Environment.Exit(1);
                return;
            }

            var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
                Environment.Exit(1);
                return;
            }
            var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

            using var client = new HttpClient();
            using var request = new HttpRequestMessage(HttpMethod.Post, baseUrl.TrimEnd('/') + "/delete");
            request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
            var content = new MultipartFormDataContent();
            content.Add(new StringContent(string.Join(',', args)), "ids");
            request.Content = content;
            var response = await client.SendAsync(request);
            var body = await response.Content.ReadAsStringAsync();
            Console.WriteLine(body);
        }
    }
}

Source: pdfRest Delete Files multipart C# sample

Track and Submit Resource IDs

The sample adds an ids form field containing a comma-separated list. A production service can build this list from the IDs recorded during the document job. Include original uploads and generated outputs only after confirming they are no longer needed. Deduplicate values and associate them with the job or tenant that created them so one workflow cannot accidentally submit another workflow's resources.

Use the same regional base URL that created the resources. The default environment setting targets the US Cloud API; PDFREST_URL can select the EU API when required. Keeping both the URL and key in deployment configuration prevents credentials and regional decisions from being embedded in source code.

The current official sample sends the request and prints the response. Application code should inspect response.IsSuccessStatusCode, parse the JSON only after confirming the status, and retain enough cleanup state to handle partial failure. A repeated cleanup attempt should be recognized and handled without masking the original job outcome.

Make Cleanup Depend on Successful Delivery

Resource cleanup belongs after final output delivery, not merely after processing. Confirm that the application has downloaded, validated, and stored every required file. If a later pdfRest call still uses an ID, wait for that operation to complete before deletion. A structured try/finally flow or a durable cleanup queue can remove abandoned resources after failures while avoiding premature deletion during retries.

Apply suitable request timeouts and cancellation tokens, handle network errors separately from API responses, and do not log document contents or secrets. Record the result needed for operational auditing without retaining unnecessary sensitive filenames.

Applications that prefer JSON can submit the IDs in a JSON body. See the official Delete Files JSON-payload C# sample. Use API Lab for request testing and consult the Delete Files API reference for the current schema.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.