简体   繁体   中英

How to store and retrieve .pdf, .exe file in SQL Server 2008

I am currently working on a Windows Forms application (C#, VS 2010) and I need to create functionality that enables users to upload .pdf , .exe files into a SQL Server 2008 database and download them back.

The problem that I have is that the file downloaded from the database is always corrupted (except .txt file) even though they are the same size. And I have used varbinary(MAX) as the file type to store the data in the database.

Can anyone show me some example code for how to do this?

PS: I have researched for more than a week, but still cannot find a solution to my problem, can anyone please help? Any answer will be highly appreciated.

In the below example there are a few assumptions made:

  1. I'm using Dapper for the database access. It extends any IDbConnection object.
  2. I have a table in the database that has a definition as such CREATE TABLE Data (Id INT IDENTITY(1, 1) PRIMARY KEY, Data VARBINARY(MAX)) .
  3. Here is the documentation for ReadAllBytes

So, obviously since you didn't provide anything surrounding your table structure you're going to have to change this code to meet you needs, but it will get you started.

Writing It

this.connection.Open();

try
{
    var parameters = new
        {
            Data = File.ReadAllBytes(...);
        };
    return connection.Execute("INSERT INTO Data (Data) VALUES (@Data)", parameters);
}
finally
{
    this.connection.Close();
}

Reading It

this.connection.Open();

try
{
    var parameters = new { Id = 1 };
    return connection.Query(
        "SELECT Data FROM dbo.Data WHERE Id = @Id", parameters)
        .Select(q => q.Data as byte[])
        .Single();
}
finally
{
    this.connection.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM