gpt4 book ai didi

c# - 从 SQL 数据库中检索 varbinary 数据字段

转载 作者:行者123 更新时间:2023-11-30 13:52:57 25 4
gpt4 key购买 nike

我正在将文件存储在数据库中,这是我正在使用的代码,它可以添加数据,但现在我想取回它。我该怎么做?

string filename = FileUploader.PostedFile.FileName;
string filecontent = FileUploader.PostedFile.ContentType;
int filesize = FileUploader.PostedFile.ContentLength;

string filepath = System.IO.Path.GetFileName(filename);


FileUploader.PostedFile.SaveAs("c:\\try\\" + filepath);

byte[] fileData = new byte[FileUploader.PostedFile.ContentLength];
FileUploader.PostedFile.InputStream.Read(fileData, 0, fileData.Length);
string originalName = Path.GetFileName(FileUploader.PostedFile.FileName);


con.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["FAQ"].ToString();

con.Open();

using (SqlCommand cmd = new SqlCommand("INSERT INTO Files(FileData) VALUES (@binaryValue)", con))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, fileData.Length).Value = fileData;
cmd.ExecuteNonQuery();
con.Close();
}

最佳答案

您可以使用 SqlDataReader获取值,BinaryWriter创建文件,像这样:

//Database connection code...
cmd.CommandText = "SELECT FileData FROM Files WHERE ID = @ID";
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 1234;
SqlDataReader sqlRead = cmd.ExecuteReader();

string fileName = "file.txt";
string fileDir = "C:\\Test\\";
string fileUrl = "/";

if (sqlRead.HasRows)
{
while(sqlRead.Read())
{
byte[] fileData = (byte[]) sqlRead[0].Value;
BinaryWriter fileCreate =
new BinaryWriter(File.Open(fileDir + fileName, FileMode.Create));
fileCreate.Write(fileData);
fileCreate.Close();
HttpResponse.Redirect(fileUrl + fileName);
}
}

sqlRead.Close();

关于c# - 从 SQL 数据库中检索 varbinary 数据字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com