[英]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. 我目前正在使用Windows Forms应用程序(C#,VS 2010),并且需要创建使用户能够将
.pdf
和.exe
文件上传到SQL Server 2008数据库并将其重新下载的功能。
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. 我的问题是,即使它们大小相同,从数据库下载的文件也总是损坏(
.txt
文件除外)。 And I have used varbinary(MAX)
as the file type to store the data in the database. 而且我已经使用
varbinary(MAX)
作为文件类型将数据存储在数据库中。
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? PS:我已经研究了一个多星期,但仍然找不到解决我问题的方法,有人可以帮忙吗? Any answer will be highly appreciated.
任何答案将不胜感激。
In the below example there are a few assumptions made: 在下面的示例中,有一些假设:
IDbConnection
object. IDbConnection
对象。 CREATE TABLE Data (Id INT IDENTITY(1, 1) PRIMARY KEY, Data VARBINARY(MAX))
. CREATE TABLE Data (Id INT IDENTITY(1, 1) PRIMARY KEY, Data VARBINARY(MAX))
。 ReadAllBytes
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.