如何从SQL Server获取图像数据,写入文件,使用C#将文件保存到磁盘

我正在尝试从SQL Server数据库中获取存储为
Image数据类型的附件(图像,word文档等).附件可以是任何文件类型,但我只是想成功下载.jpg.

我可以将文件保存到本地驱动器,但它似乎在整个过程中损坏了文件.

我正在尝试做什么:

>从SQL Server数据库中检索IMAGE类型的二进制数据.
>从二进制数据创建文件.
>将文件保存到本地目录.

我的代码:

    public void ProcessRequest()
    {
        //Get the ticket number from query string
        _ticketNumber = context.Request.QueryString["ID"];

        SqlConnection conn = new SqlConnection(_DBConn);
        SqlCommand cmd = new SqlCommand();
        string fileName = ""; //Holds the file name retrieved from DB
        byte[] data; // Holds the IMAGE data from DB

        using (conn)
        {
            using (cmd)
            {

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = @"SELECT File_Name, Data FROM Tickets_All INNER JOIN Attachments ON Tickets_All.ID = Attachments.[Object_ID] WHERE Ticket = @Ticket";
                cmd.Parameters.AddWithValue("@Ticket", _ticketNumber);
                cmd.Connection = conn;
                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        fileName = reader.GetString(0);
                        data = (byte[])reader["Data"];

                        if (data != null)
                        {
                            SaveData(fileName, data);
                        }
                    }
                }

                reader.Close();

            }
        }

    protected bool SaveData(string FileName, byte[] Data)
    {
        string path = @"C:\Windows\temp\test.jpg";

        try
        {
            BinaryWriter writer = new BinaryWriter(File.OpenWrite(path));
            writer.Write(Data);
            writer.Flush();
            writer.Close();
        }
        catch (Exception ex)
        {
            return false;
        }

        return true;
    }

如果代码不符合最佳实践,请原谅我,我更多的是VB程序员,我以前从未这样做过.我只想尝试一个有效的例子.

提前致谢.

最佳答案 我会使用Image.FromStream方法执行此操作:

http://msdn.microsoft.com/en-us/library/system.drawing.image.fromstream(v=vs.110).aspx

protected bool SaveData(string FileName, byte[] Data)
{
    using (Image image = Image.FromStream(new MemoryStream(Data)))
    {
        image.Save("MyImage.jpg", ImageFormat.Jpeg);
    }

    return true;
}
点赞