Corey Masson
Corey Masson

Reputation: 31

sqlfilestream - getting blob data from SQL Server and saving the file locally to disk

I have the following scenario:

I have successfully saved my files(various extensions) into my sql server db using FILESTREAM. These can be anything from an image, to a word doc, pdf etc.

now i want to retreive them and save them as a file to my local directory.

here is what i have so far

My function calling SQL and getting the the filestream information i want

    public static void SelectFile(string sourceId)
    {
        string serverPath;
        string filename;
        byte[] serverTxn;

        using (TransactionScope ts = new TransactionScope())
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConn"].ToString()))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand("OPS.LoadFileBlobFromSQL", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@AttachmentId", SqlDbType.VarChar).Value = sourceId;

                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        filename = rdr.GetSqlString(0).Value;
                        serverPath = rdr.GetSqlString(1).Value;
                        serverTxn = rdr.GetSqlBinary(2).Value;
                        rdr.Close();
                    }
                }
               StreamObjectFromFilestream(serverPath, serverTxn, filename);
            }
            ts.Complete();
        }
    }

    private static void StreamObjectFromFilestream(string serverPath, byte[] serverTxn, string filename)
    {
        SqlFileStream sfs = new SqlFileStream(serverPath, serverTxn, FileAccess.Read);
        byte[] buffer = new byte[sfs.Length];
        sfs.Read(buffer, 0, buffer.Length);

        System.IO.File.WriteAllBytes(@"c:\test\hello.pdf", buffer);
        sfs.Close();
    }

I am getting serverpath, filename and serverTxn .. but when i go into my StreamObjectFromFilestream function the buffer is empty.. i know i am missing something simple here ... just dont know what.

Any pointers in the right direction would be appreciated.

Thanks, Corey

Upvotes: 3

Views: 727

Answers (1)

Lorien
Lorien

Reputation: 160

You can skip using the SqlFilestream inside StreamObjectFromFilestram, your serverTxn is already a byte array that the Method WriteAllBytes is needing.

Upvotes: 1

Related Questions