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

时间:2021-09-17 21:21:39

I'm trying to get attachments (images, word documents, etc.) stored as an Image datatype from a SQL Server database. The attachments can be of any file type, but I'm just trying to get a .jpg to download successfully.

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

I'm able to save the file to my local drive, but it appears to be corrupting the file in the process.

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

What I'm trying to do:

我想做什么:

  1. Retrieve binary data of type IMAGE from SQL Server Database.
  2. 从SQL Server数据库中检索IMAGE类型的二进制数据。
  3. Create a file from the binary data.
  4. 从二进制数据创建文件。
  5. Save the file to a local directory.
  6. 将文件保存到本地目录。

My CODE:

我的代码:

    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;
    }

Please forgive me if the code isn't up to par with best practices, I'm more of a VB programmer and I've never had to do this before. I'm just trying to get a working example.

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

Thanks in advance.

提前致谢。

2 个解决方案

#1


2  

I would use the Image.FromStream method to do this : http://msdn.microsoft.com/en-us/library/system.drawing.image.fromstream(v=vs.110).aspx

我将使用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;
}

#2


0  

Thanks for the input everyone. After doing some additional testing, I think that the data being retrieved from the database has been compressed in some way. I'm able to insert and pull out files programmatically just fine, the problem comes in when the application puts the data into the database (3rd party software). I'm going to look into the compression what I can come up with.

感谢大家的意见和建议。在做了一些额外的测试之后,我认为从数据库中检索的数据已经以某种方式被压缩了。我能够以编程方式插入和拔出文件,当应用程序将数据放入数据库(第三方软件)时会出现问题。我将研究压缩我能想出什么。

#1


2  

I would use the Image.FromStream method to do this : http://msdn.microsoft.com/en-us/library/system.drawing.image.fromstream(v=vs.110).aspx

我将使用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;
}

#2


0  

Thanks for the input everyone. After doing some additional testing, I think that the data being retrieved from the database has been compressed in some way. I'm able to insert and pull out files programmatically just fine, the problem comes in when the application puts the data into the database (3rd party software). I'm going to look into the compression what I can come up with.

感谢大家的意见和建议。在做了一些额外的测试之后,我认为从数据库中检索的数据已经以某种方式被压缩了。我能够以编程方式插入和拔出文件,当应用程序将数据放入数据库(第三方软件)时会出现问题。我将研究压缩我能想出什么。