上传文件到SQL Server,无法正确检索

我的问题是以下几点:我试图用这个方法上传一个Excel文件到数据库:

using (SqlConnection connection = new SqlConnection(@"Data Source=TESZT1\SQLEXPRESS;Initial Catalog=Alepitmeny;Persist Security Info=True;User ID=sa;Password=*****")) using (SqlCommand command = connection.CreateCommand()) { byte[] file; using (var stream = new FileStream(ExcelFilePath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { file = reader.ReadBytes((int)stream.Length); } } command.CommandText = "INSERT INTO Dokumentacio (Elrendelo_ExcelFile) VALUES (@File) SELECT SCOPE_IDENTITY()"; command.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file; connection.Open(); this.dokumentacio_Class.Dokumentacio_ID = Convert.ToInt32(command.ExecuteScalar()); connection.Close(); } 

但是当我用下面的方法下载上传的文件,我得到一个错误信息

Excel在filename.xls中发现不可读的内容。 你想恢复这个工作簿的内容?

从Microsoft Excel,它不能恢复它。

(我使用的是SQL Server 2012,Visual Studio 2013,该项目是WPF项目,我的Office版本是2013)

在数据库中, Elrendelo_ExcelFile列是VARBINARY(MAX)

  public bool ElrendeloExcelFileLetolt(string SavePath) { using (SqlConnection connection = new SqlConnection(@"Data Source=TESZT1\SQLEXPRESS;Initial Catalog=Alepitmeny;Persist Security Info=True;User ID=sa;Password=*****")) try { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"SELECT d.Elrendelo_ExcelFile FROM Dokumentacio d INNER JOIN Kapcsolotabla k ON k.Dokumentacio_ID=d.Dokumentacio_ID WHERE k.Elrendelo_ID=@id"; command.Parameters.AddWithValue("@id", this.dokumentacio_ID); FileStream stream; BinaryWriter writer; int bufferSize = 100; byte[] buffer = new byte[bufferSize]; long retval; long startIndex = 0; connection.Open(); SqlDataReader reader = command.ExecuteReader(CommandBehavior.Default); while (reader.Read()) { stream = new FileStream(SavePath, FileMode.OpenOrCreate, FileAccess.Write); writer = new BinaryWriter(stream); startIndex = 0; retval = reader.GetBytes(0, startIndex, buffer, 0, bufferSize); while (retval == bufferSize) { writer.Write(buffer); writer.Flush(); startIndex += bufferSize; retval = reader.GetBytes(0, startIndex, buffer, 0, bufferSize); } writer.Write(buffer, 0, (int)retval - 1); writer.Flush(); writer.Close(); stream.Close(); } reader.Close(); connection.Close(); } return true; } catch (System.Data.SqlClient.SqlException) { return false; } finally { connection.Close(); } } 

这样的答案应该可以帮助你 – > 如何在SQL Server 2008中插入/检索Excel文件到varbinary(max)列?