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 5: <strong>FILESTREAM</strong> with ASP.NET and Silverlight//Begin a transactionSqlTransaction transaction = cn.BeginTransaction("ItemTran");cmd.Transaction = transaction;byte[] txContext = null;string filePath = string.Empty;try{//Execute the commandSqlDataReader reader = cmd.ExecuteReader();if (reader.Read()){txContext = (reader["txContext"] as byte[]);filePath = reader["filePath"].ToString();}Reader.Close();//Open the <strong>FILESTREAM</strong> data file for writingSqlFileStream fs = new SqlFileStream(filePath, txContext,FileAccess.Write);//Get a stream object pointing to the content to be uploadedStream localFile = fpItemImage.FileContent;//Start transferring data into <strong>FILESTREAM</strong> data file// If you are using .NET 4.0 the next 11 lines <strong>of</strong> code can be// replaced with a single call to "localFile.CopyTo(fs, 4096);"BinaryWriter bw = new BinaryWriter(fs);const int bufferSize = 4096;byte[] buffer = new byte[bufferSize];int byteCount = localFile.Read(buffer, 0, bufferSize);while (byteCount == bufferSize){bw.Write(buffer, 0, bytes);bw.Flush();byteCount = localFile.Read(buffer, 0, bufferSize);}Bw.Close();}//Close the fileslocalFile.Close();fs.Close();174

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

Saved successfully!

Ooh no, something went wrong!