要使用C#将PDF文件插入和读取到SQL Server数据库,您需要遵循以下步骤:
您可以使用NuGet包管理器将这些库添加到您的项目中。
CREATE TABLE PdfFiles (
Id INT PRIMARY KEY IDENTITY(1,1),
FileName NVARCHAR(MAX),
Content VARBINARY(MAX)
);
using iTextSharp.text.pdf;
using System.IO;
public byte[] ConvertPdfToByteArray(string pdfPath)
{
byte[] pdfBytes;
using (var pdfReader = new PdfReader(pdfPath))
{
using var memoryStream = new MemoryStream();
using var pdfStamper = new PdfStamper(pdfReader, memoryStream);
pdfStamper.Close();
pdfBytes = memoryStream.ToArray();
}
return pdfBytes;
}
using System.Data.SqlClient;
public void InsertPdfIntoDatabase(string pdfPath, string fileName, string connectionString)
{
byte[] pdfBytes = ConvertPdfToByteArray(pdfPath);
using var connection = new SqlConnection(connectionString);
connection.Open();
using var command = new SqlCommand("INSERT INTO PdfFiles (FileName, Content) VALUES (@FileName, @Content)", connection);
command.Parameters.AddWithValue("@FileName", fileName);
command.Parameters.AddWithValue("@Content", pdfBytes);
command.ExecuteNonQuery();
}
using System.Data.SqlClient;
using System.IO;
public void ReadPdfFromDatabase(int pdfId, string outputPath, string connectionString)
{
using var connection = new SqlConnection(connectionString);
connection.Open();
using var command = new SqlCommand("SELECT Content FROM PdfFiles WHERE Id = @Id", connection);
command.Parameters.AddWithValue("@Id", pdfId);
using var reader = command.ExecuteReader();
if (reader.Read())
{
byte[] pdfBytes = (byte[])reader["Content"];
using var pdfReader = new PdfReader(pdfBytes);
using var pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));
pdfStamper.Close();
}
}
现在,您可以使用这些方法将PDF文件插入和读取到SQL Server数据库。请注意,这些方法仅用于演示目的,实际应用中可能需要进行错误处理和优化。
领取专属 10元无门槛券
手把手带您无忧上云