首页 > 解决方案 > 从数据库中获取 PDF 文件并将其显示在 Windows 窗体 C#

问题描述

我想使用它的位置从数据库中获取一个 PDF 文件并将其显示在我的表单应用程序上。我看了很多 Youtube 视频,但没有一个能帮助我解决我的问题。我可以尝试这样做的其他方法是什么?

string f = comboBox2.Text;
string qu = "SELECT location FROM attachments WHERE name='" + f + "'";

SqlCommand com = new SqlCommand(qu, con);
SqlDataReader reader = com.ExecuteReader();

while (reader.Read())
{
    var input = reader["location"].ToString();
    this.axAcroPDF1.LoadFile(input);
}

我的数据库表看起来像

CREATE TABLE [dbo].[attachments]  
(
    [Id]       INT           IDENTITY (1, 1) NOT NULL,
    [idno]     INT           NULL,
    [name]     VARCHAR (MAX) NULL,
    [location] VARCHAR (MAX) NULL
);

我没有从任何有关此问题的视频中获得任何帮助。任何建议如何改进此代码?

标签: c#winformspdf

解决方案


将位置字段更改为 VarBinary。

CREATE TABLE [dbo].[attachments] (
[Id]       INT           IDENTITY (1, 1) NOT NULL,
[idno]     INT           NULL,
[name]     VARCHAR (MAX) NULL,
[location] VARBINARY (MAX) NULL
);

如果 LoadFile 方法将接受它,则使用字节数组,否则写入磁盘...

string f = comboBox2.Text;
string qu = "SELECT location FROM attachments WHERE name=@name";

SqlCommand com = new SqlCommand(qu, con);
com.Parameters.Add(new SqlParameter("@name", f);
SqlDataReader reader = com.ExecuteReader();

while (reader.Read())
{
    var file = (byte[])reader["location"];
    this.axAcroPDF1.LoadFile(file);
    //else use a method like 'File.WriteAllBytes(file);'
}

推荐阅读