dir.by  
Поиск >>

Компьютер, программы
→
ADO.NET (working with the database on C#)
 Read the image from the database and save it to a file | ADO.NET, C# 
посмотрели 4252 раз
обновлено: 22 July 2025
Download an example:
Note! You must have Microsoft SQL Server installed. If you don't have it, then need to download and install Microsoft SQL Server ...

Note! You must have SQL Server Management Studio installed. If you don't have it, then need to download and install SQL Server Management Studio ...
Step 1. Open (run) SQL Server Management Studio. In the Database, create the table Books
Create a new database named MyDatabase1
You need to press refresh
Create the Books table
Step 2. Let's create ADO.NET console application on C#
Step 3. Let's write the code
  C#     Write the code in the file Program.cs
using Microsoft.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;

namespace ConsoleApp1
{
     internal class Program
     {
          static void Main(string[] args)
          {
               string connectString = @"Data Source=localhost;Initial Catalog=MyDatabase1;Integrated Security=True; Trust Server Certificate=True";

               // Store image in Database
               byte[] imgFile = File.ReadAllBytes(@"D:/file1.png");
               AddImageToDatabase(connectString,
                    "Books", // table
                    1, // id = 1
                    imgFile,
                    "Id",
                    "Icon"
                    );

               // get image from database
               byte[] imageFromDatabase = GetDatabaseImage(connectString,
                    "Books", // table
                    1, // id = 1
                    "Id",
                    "Icon"
                    );
               // store to file
               File.WriteAllBytes(@"D:\file1.png", imageFromDatabase);
          }

          static byte[] GetDatabaseImage(string connectString, string tableName, int id, string columnNameForId, string columnNameForImage)
          {
               byte[] imageResult = null;
               using (SqlConnection connection = new SqlConnection(connectString))
               {
                    string sqlExpression = $"SELECT {columnNameForImage} FROM {tableName} where {columnNameForId}={id}";
                    using (SqlCommand cmd = new SqlCommand(sqlExpression, connection))
                    {
                         connection.Open();
                         using (SqlDataReader reader = cmd.ExecuteReader())
                         {
                              while (reader.Read())
                              {
                                   SqlBytes sqlBytes = reader.GetSqlBytes(0);
                                   imageResult = new byte[sqlBytes.Length];
                                   sqlBytes.Read(0, imageResult, 0, (int)imageResult.Length);
                              }
                         }
                         connection.Close();
                    }
               }
               return imageResult;
          }
          static void AddImageToDatabase(string connectString, string tableName, int id, byte[] imageBytes, string columnName1, string columnName2)
          {
               using (SqlConnection connection = new SqlConnection(connectString))
               {
                    string sqlExpression = $"INSERT INTO {tableName} ({columnName1}, {columnName2}) Values (@param1, @param2)";
                    using (SqlCommand cmd = new SqlCommand(sqlExpression, connection))
                    {
                         cmd.Parameters.Add(new SqlParameter("@param1", id));
                         cmd.Parameters.Add(new SqlParameter("@param2", imageBytes));
                         connection.Open();
                         cmd.ExecuteNonQuery();
                         connection.Close();
                    }
               }
          }
     }
}
 
← Previous topic
Transactions in ADO.NET | Database in the C# console application
 
Next topic →
Database connection string | ADO.NET, C#
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
• What is ADO.NET?
• Let"s create a ADO.NET console application (C#, database)
Working with data in ADO.NET
• Read the data (select) from the Database using SqlCommand and SqlDataReader in ADO.NET C#. Database Type Mapping
• Read (select) data from the Database using SqlDataAdapter and DataSet | ADO.NET, C#
• Get a scalar (single) value: Count, Min, Max, Sum, etc. | ADO.NET, C#
• Add data (insert into) to the Database using SqlCommand | ADO.NET, C#
• Change the data (update) in the Database using SqlCommand | ADO.NET, C#
• Delete data in the Database using SqlCommand | ADO.NET, C#
Stored procedures in ADO.NET
• Stored procedures in ADO.NET | C#
Transactions in ADO.NET
• Transactions in ADO.NET | Database in the C# console application
Reading the picture from the database ADO.NET
• Read the image from the database and save it to a file | ADO.NET, C#
Additional topics, questions
• Database connection string | ADO.NET, C#

  Ваши вопросы присылайте по почте: info@dir.by