MySQL load BLOB as stream to file (async)

Date: 2024-10-08

See also: https://solidt.eu/site/c-download-file-from-database-as-stream/

using MySql.Data.MySqlClient; // Zorg ervoor dat MySqlConnector is geïnstalleerd (MySql.Data)
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string connectionString = "Server=your_server;Database=your_database;User ID=your_user;Password=your_password;";
        string query = "SELECT blob_column FROM your_table WHERE id = @Id";
        int id = 1; // Stel dit in op de id-waarde van het record dat je wilt ophalen

        await ReadBlobToFileUsingStreamAsync(connectionString, query, id, "output_file_path");
    }

    static async Task ReadBlobToFileUsingStreamAsync(string connectionString, string query, int id, string filePath)
    {
        using (var connection = new MySqlConnection(connectionString))
        {
            await connection.OpenAsync();
            using (var command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@Id", id);

                using (var reader = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess)) 
                {
                    if (await reader.ReadAsync())
                    {
                        // Haal de index van de kolom op, in dit voorbeeld is de kolomnaam "blob_column"
                        int blobColumnIndex = reader.GetOrdinal("blob_column");

                        // Verkrijg een stream van de BLOB-kolom
                        using (Stream blobStream = reader.GetStream(blobColumnIndex))
                        using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                        {
                            // Kopieer de BLOB-stream asynchroon naar de FileStream
                            await blobStream.CopyToAsync(fileStream);
                            Console.WriteLine($"BLOB-gegevens succesvol geschreven naar {filePath}.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Geen gegevens gevonden voor het opgegeven ID.");
                    }
                }
            }
        }
    }
}
89590cookie-checkMySQL load BLOB as stream to file (async)