PDF file in a database using C#,
To save a PDF file in a database using C#, the common approach involves
converting the PDF into a byte array and then storing this binary data in a suitable
database column.
1. Database Schema:
Create a table with a column designed to store binary data. In SQL Server, this
would typically be a VARBINARY(MAX) column. You might also want columns for
metadata like filename, content type, and file size.
Code
CREATE TABLE Documents (
DocumentID INT IDENTITY(1,1) PRIMARY KEY,
FileName NVARCHAR(255),
ContentType NVARCHAR(100),
FileSize BIGINT,
FileData VARBINARY(MAX)
);
2. C# Code for Saving:
The following steps outline how to convert a PDF file to a byte array and save it to
the database:
• Read the PDF file into a byte array: Use System.IO.File.ReadAllBytes() or
a FileStream and BinaryReader to read the PDF content into a byte[].
• Establish a database connection: Use SqlConnection and specify your
connection string.
• Create and execute an SqlCommand: Use an INSERT statement to add the byte
array to the FileData column. Parameterize your query to prevent SQL
injection.
Code
using System;
using System.Data.SqlClient;
using System.IO;
public class PdfSaver
{
public static void SavePdfToDatabase(string filePath, string
connectionString)
{
try
{
// Read the PDF file into a byte array
byte[] pdfBytes = File.ReadAllBytes(filePath);
string fileName = Path.GetFileName(filePath);
string contentType = "application/pdf"; // Or dynamically
determine from file extension
long fileSize = pdfBytes.Length;
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Documents (FileName,
ContentType, FileSize, FileData) VALUES (@FileName, @ContentType,
@FileSize, @FileData)";
PDF file in a database using C#,
using (SqlCommand command = new SqlCommand(query,
connection))
{
command.Parameters.AddWithValue("@FileName", fileName);
command.Parameters.AddWithValue("@ContentType",
contentType);
command.Parameters.AddWithValue("@FileSize", fileSize);
command.Parameters.AddWithValue("@FileData", pdfBytes);
command.ExecuteNonQuery();
Console.WriteLine("PDF saved to database
successfully.");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error saving PDF: {ex.Message}");
}
}
}
3. Retrieving and Displaying/Downloading:
To retrieve and use the PDF:
• Query the database: to retrieve the FileData (byte array) and other
metadata.
• Convert the byte array back to a file: if needed, or stream it directly to a
client for download by setting appropriate HTTP headers (Content-
Disposition, Content-Type).