我有一个项目,我将文档作为 blob 存储在 MySQL 数据库中,并使用 C# 将它们下载为字节数组:
public static byte[] GetFile(string fileName)
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ...
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (reader.HasRows)
{
return Util.ObjectToByteArray(reader["Content"]);
}
...
}
...
public static byte[] ObjectToByteArray(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
我像这样上传文件:
byte[] newFile = File.ReadAllBytes(fileName);
然后像这样下载:
File.WriteAllBytes(path + "\\" + selectedFileName,
DocumentTable.GetFile(selectedFileName));
但是当我下载文件时,它们已损坏并且无法打开(例如Excel文件,一些其他类型可以打开)。下载文件的扩展名似乎是正确的,但我收到消息“文件扩展名或文件格式无效”。
最佳答案
我建议使用数据读取器的 GetStream() 重写;
content = reader.GetStream(1);
并简单地将流对象返回给您的文件编写器。
关于C#:作为字节数组下载后文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41742938/