简体   繁体   English

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

[英]C#: file corrupted after downloading as byte array

I have a project in which I store documents as blobs in a MySQL database, and download them as byte arrays using C#: 我有一个项目,其中将文档作为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();
    }
}

I upload the files like this: 我这样上传文件:

byte[] newFile = File.ReadAllBytes(fileName);

and download like this: 并像这样下载:

File.WriteAllBytes(path + "\\" + selectedFileName, 
                   DocumentTable.GetFile(selectedFileName));

but when I download the files, they are corrupted and cannot be opened (for example Excel files, some other types can be opened). 但是当我下载文件时,它们已损坏并且无法打开(例如,Excel文件,可以打开某些其他类型)。 The extension of the downloaded file seems to be correct, but I am getting the message that "the file extension or file format are not valid". 下载的文件的扩展名似乎正确,但是我收到消息“文件扩展名或文件格式无效”。

I recommend using the GetStream() override of the data reader; 我建议使用数据读取器的GetStream()重写;

content = reader.GetStream(1);

and simply returning the stream object to your File writer. 并简单地将流对象返回给您的File writer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM