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

Why Delete Files with C#?

The pdfRest Delete Files API Tool is a powerful feature that allows developers to programmatically delete files from their pdfRest account using an API call. This tutorial will guide you through the process of sending an API call to delete files using C#. By integrating this functionality into your C# applications, you can automate the management of files.

For instance, after a process is complete, a developer might use the Delete Files API to immediately delete all related temporary or intermediate documents instead of waiting for the default 30-minute retention period to expire. This allows them to ensure data is removed instantly when no longer needed, providing maximum control over their files.

Delete Files with C# Code Example

/*
 * What this sample does:
 * - Deletes multiple resources by ids.
 * - Routed from Program.cs as: `dotnet run -- batch-delete-multipart  [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  [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: GitHub Repository

Breaking Down the Code

The code begins by checking if the necessary arguments are provided. If not, it outputs an error message and exits the program:

if (args == null || args.Length < 1)
{
    Console.Error.WriteLine("batch-delete-multipart requires  [id2] [...]");
    Environment.Exit(1);
    return;
}

Next, it retrieves the API key from the environment variables. This key is essential for authenticating with the pdfRest API:

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

The base URL for the API is set, with an option to override it for EU/GDPR compliance:

var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

An HTTP client and request are created to send a POST request to the delete endpoint:

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Post, baseUrl.TrimEnd('/') + "/delete");
request.Headers.TryAddWithoutValidation("Api-Key", apiKey);

The IDs of the files to be deleted are added to the request as multipart form data:

var content = new MultipartFormDataContent();
content.Add(new StringContent(string.Join(',', args)), "ids");
request.Content = content;

The request is sent asynchronously, and the response is printed to the console:

var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);

Beyond the Tutorial

In this tutorial, you've learned how to use C# to call the pdfRest Delete Files API to delete files programmatically. This capability can be a vital part of managing your document storage efficiently. To explore more functionalities, try out all the pdfRest API Tools in the API Lab. For more detailed information, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub Repository.

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