【发布时间】:2025-12-10 20:55:02
【问题描述】:
我有一个包含两个表的数据集。第一个告诉我它是一个 doc 文件。第二个包含文件的字节数组。但是我需要取出前 85 个字节,因为它们包含由 Access 创建的 OLE 对象标头。到目前为止我有这个。 .
protected void Page_Load(object sender, EventArgs e)
{
int examId = Convert.ToInt32(Request.QueryString["exam_id"]);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RHD_CS"].ConnectionString);
try
{
conn.Open();
}
catch (Exception)
{
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_spirometry_readexam";
cmd.Parameters.Add("@iExamID", SqlDbType.Int);
cmd.Parameters["@iExamID"].Value = examId;
string sFileName = "exam" + examId.ToString()+".";
DataSet dsData = new DataSet();
SqlDataAdapter daData = new SqlDataAdapter(cmd);
daData.Fill(dsData);
DataRow drDocData = dsData.Tables[1].Rows[0];
byte[] bDocData = (byte[])drDocData["exam_binary"];
Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename= filename.doc");
Response.BinaryWrite(bDocData);
Response.End();
这行得通,但是当文件被下载时,它只是一堆乱码。
已解决 感谢所有的帮助。我通过使用流然后将其转换回字节解决了这个问题。
protected void Page_Load(object sender, EventArgs e)
{
int examId = Convert.ToInt32(Request.QueryString["exam_id"]);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RHD_CS"].ConnectionString);
try
{
conn.Open();
}
catch (Exception)
{
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_spirometry_readexam";
cmd.Parameters.Add("@iExamID", SqlDbType.Int);
cmd.Parameters["@iExamID"].Value = examId;
string sFileName = "exam" + examId.ToString()+".";
DataSet dsData = new DataSet();
SqlDataAdapter daData = new SqlDataAdapter(cmd);
daData.Fill(dsData);
DataRow drDocData = dsData.Tables[1].Rows[0];
byte[] bDocData = (byte[])drDocData["exam_binary"];
Label1.Text = bDocData.Length.ToString();
Stream stream = new MemoryStream(bDocData);
stream.Position = 85;
bDocData = ReadFully(stream);
Response.Clear();
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename= insert filename.doc");
Response.BinaryWrite(bDocData);
Response.End();
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
【问题讨论】:
-
<byte[]>.Skip(85)用于数据。标题是<byte[]>.Take(85)?请注意,<byte[]>是一个占位符。 -
@FᴀʀʜᴀɴAɴᴀᴍ 这将在我的代码中出现在哪里?我会对我的 bDocData 数组执行此操作吗?
-
是的,您需要从中提取标头和数据的字节[]
标签: c# sql asp.net stream bytearray