17.07.2015 Views

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: Accessing <strong>FILESTREAM</strong> Data from Client ApplicationsSqlTransaction transaction = con.BeginTransaction("ItemTran");cmd.Transaction = transaction;SqlDataReader reader = cmd.ExecuteReader();if (reader.Read()){txContext = (reader["txContext"] as byte[]);filePath = reader["filePath"].ToString();}reader.Close();Listing 3-15:Inserting a record and retrieving the <strong>FILESTREAM</strong> file path and transaction context.Once we have the logical path to the <strong>FILESTREAM</strong> data file and the <strong>FILESTREAM</strong>transaction context, we can write the binary data (the content <strong>of</strong> the disk file that storesthe image) into the <strong>FILESTREAM</strong> store, as shown in Listing 3-16.//Open the <strong>FILESTREAM</strong> data file for writingSqlFileStream fs = new SqlFileStream(filePath, txContext,FileAccess.Write);// Open the disk file for readingFileStream localFile = new FileStream("C:\\temp\\micros<strong>of</strong>tmouse.jpg",FileMode.Open, FileAccess.Read);//Copy data from disk file to <strong>FILESTREAM</strong> columnlocalFile.CopyTo(fs, 4096);Listing 3-16:Writing the content <strong>of</strong> a byte array into a <strong>FILESTREAM</strong> data file.And finally, we close the <strong>FILESTREAM</strong> file, commit the transaction, and close thedatabase connection to complete the exercise (Listing 3-17).//Close the fileslocalFile.Close();fs.Close();108

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!