将Binary转换为Byte []数组

时间:2011-07-05 12:57:36

标签: c# asp.net database

如何将存储在我的数据库字段中的二进制数据转换为Byte []数组?

简单地将二进制文件转换为byte []不起作用

context.Response.BinaryWrite((byte[])images);

2 个答案:

答案 0 :(得分:5)

如果图像是Binary类型的单个记录,则调用toArray应该可以正常工作

 context.Response.BinaryWrite(images.toArray());

答案 1 :(得分:2)

public byte[] FileToByteArray(string _FileName)    
{

        byte[] _Buffer = null;

       try
        {
            // Open file for reading
            System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            // attach filestream to binary reader
            System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

            // get total byte length of the file
            long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

            // read entire file into buffer
            _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);

            // close file reader
            _FileStream.Close();
            _FileStream.Dispose();
            _BinaryReader.Close();
        }
        catch (Exception _Exception)
        {
            // Error
            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        }

        return _Buffer;
}