如何将文本文件数据从数据库检索到文本框?
问题描述:
实际上我将一个文本文件上传到数据库,现在我需要将该数据放入文本框(多行)
我为文件上传编写的代码
=======================================
Actually i uploaded a text file to database and now i need to get that data into a textbox(multiline)
code that i have written for file upload
========================================
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile == null || string.IsNullOrEmpty(FileUpload1.PostedFile.FileName) || FileUpload1.PostedFile.InputStream == null)
{
Label1.Text =
"<br />Error - unable to upload file. Please try again.<br />";
}
else
{
string SQL = "INSERT INTO FileUpLoad values(@FileName, @DateTime, @MIME, @BinaryData)";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("@FileName", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@DateTime", DateTime.Now);
cmd.Parameters.AddWithValue("@MIME", FileUpload1.PostedFile.ContentType);
byte[] imageBytes = new byte[FileUpload1.PostedFile.InputStream.Length + 1];
FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
cmd.Parameters.AddWithValue("@BinaryData", imageBytes);
con.Open();
cmd.ExecuteNonQuery();
Label1.Text = "<br />File successfully uploaded - thank you.<br />";
con.Close();
}
con.Close();
}
答
using(SqlCommand cmd = new SqlCommand("SELECT BinaryData FROM FileUpload", connection))
{
byte[] file = (byte)cmd.ExexcuteScalar();
MemoryStream ms = new MemoryStream(file, true);
ms.Write(file, 0, file.Length);
using(StreamReader reader = new StreamReader(ms))
{
textbox.Text = reader.ReadToEnd();
}
}