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:
IDbConnection
object. CREATE TABLE Data (Id INT IDENTITY(1, 1) PRIMARY KEY, Data VARBINARY(MAX))
. 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.
this.connection.Open();
try
{
var parameters = new
{
Data = File.ReadAllBytes(...);
};
return connection.Execute("INSERT INTO Data (Data) VALUES (@Data)", parameters);
}
finally
{
this.connection.Close();
}
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.