C#:文件在下载后作为字节数组损坏

时间:2017-01-19 13:26:09

标签: c# mysql blob file-format

我有一个项目,我将文档作为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文件,可以打开其他一些类型)。下载文件的扩展名似乎是正确的,但我收到的消息是“文件扩展名或文件格式无效”。

1 个答案:

答案 0 :(得分:1)

我建议使用数据读取器的GetStream()覆盖;

content = reader.GetStream(1);

并简单地将流对象返回到您的文件编写器。