A small C# program to extract BLOB content from a Oracle database to my harddrive



I needed a small program to extract BLOB content from a Oracle 11g database.

So i wrote it quick & dirty and want to share it with you:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlobLeecher
{
    class Program
    {
        private static DataTable returnDataTable;
        public static bool success = true;

        public static string outputDir = "C:\\temp\\output\\";

        static void Main(string[] args)
        {
            string queryString = "SELECT t.binary_id, t.file_name, t.mime_type, t.data_size, t.data FROM binary_files t where t.mime_type is not null order by t.binary_id";
            string connectionString = "Data Source=<database>;User Id=<user>;Password=<password>;";

            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand command = new OracleCommand(queryString, connection);
                connection.Open();
                OracleDataReader reader = command.ExecuteReader();
                try
                {
                    while (reader.Read())
                    {

                        int fileId = reader.GetInt32(0);
                        string fileName = reader.GetString(1);
                        string fileMimeType = reader.GetString(2).ToString();
                        int fileSize = reader.GetInt32(3) / 1024;

                        Console.WriteLine(fileId + ", " + fileName + ", " + fileMimeType + ", " + fileSize / 1024 + "kb");

                        using (FileStream stream = File.Open(outputDir + fileId + "_" + fileName, FileMode.Create))
                        {
                            OracleLob ol = reader.GetOracleLob(4);

                            byte[] buffer = new byte[4096];
                            int len = ol.Read(buffer, 0, buffer.Length);
                            while (len > 0)
                            {
                                stream.Write(buffer, 0, len);
                                len = ol.Read(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }

            Console.WriteLine("\n\nfinished...\n");
            Console.ReadLine();
        }
    }
}

If you have questions, just comment...


Comments