C# 正在将文件上载到SQL Server,无法正确检索该文件
我的问题如下:我正在尝试使用此方法将Excel文件上载到数据库:C# 正在将文件上载到SQL Server,无法正确检索该文件,c#,sql-server,database,excel,file-upload,C#,Sql Server,Database,Excel,File Upload,我的问题如下:我正在尝试使用此方法将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.CreateComma
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\u ExcelFile
列是VARBINARY(MAX)
这个答案应该对你有所帮助->我想做一个方法,将excel文件保存到数据库中,还有一个方法,可以正确地检索它。看起来你正在尝试开发一个DMS(文档管理系统)-正确吗?不正确。我的输入数据是excel文件格式。我从中收集信息,并在我的程序中使用它们,但我想保存实际的文件供以后使用。因此,将使用我的程序的用户可以稍后下载原始输入文件。好的,我已经修改了我的答案。谢谢,尽管我一直在搜索这个主题,但我找不到该线程。你帮了我很多。
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();
}
}