C# 保存后文件大小增加1KB

C# 保存后文件大小增加1KB,c#,sql,sql-server,C#,Sql,Sql Server,我正在SQL Server列数据类型varbinarymax中保存图像文件。在数据库中保存文件的代码: Stream fs = imgUpload.PostedFile.InputStream; BinaryReader br = new BinaryReader(fs); Byte[] bytes = br.ReadBytes((Int32)fs.Length); SqlConnection conn = new SqlConnection(System.Configuration.Conf

我正在SQL Server列数据类型varbinarymax中保存图像文件。在数据库中保存文件的代码:

Stream fs = imgUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);

SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();

using (SqlCommand cmd = new SqlCommand("update tbEHUsers set photo=@binaryValue where UserID="+Session["UserID"].ToString(), conn))
{                        
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, -1).Value = bytes;
    cmd.ExecuteNonQuery();
}
conn.Close();
从SQL Server获取图像数据:

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
con.Open();
SqlCommand CMD = new SqlCommand("SELECT Photo from tbEHUsers where UserID=" + Session["UserID"], con);
SqlDataReader rdr = CMD.ExecuteReader();
byte[] imgArray = null;

while (rdr.Read())
{
        imgArray = (byte[])rdr["Photo"];
}

File.WriteAllBytes("D:\\Test12345.jpg", imgArray);
我上传的文件的原始大小是858KB,但在从数据库检索并使用file.writealBytes方法再次保存后,它增加到859KB。现在,当我试图打开这个文件时,我得到了“损坏的文件错误”。在保存和检索时,字节数组大小相同


我做错了什么???

当使用FileUpload.PostedFile时,您需要重置InputStream以重新开始。因此,在代码顶部添加以下行:

imgUpload.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);

使用十六进制编辑器比较文件。要插入的额外数据在哪里?一开始?最后?重要的是,插入的是什么?您应该在查询中为UserID使用一个参数!