title: How do I OPEN a stored excel file in SQL Server 2008 via C#
body: <p>I have stored an excel file in my SQL Server 2008 DB (as a VARBINARY(MAX)) the following (so far, hard coded) way:</p>
  
  <pre><code>// C# - visual studio 2008
  var update = new SqlCommand("UPDATE Requests SET Attachment = @xls" +
          " WHERE RequestsID = 27", conn);
       update.Parameters.AddWithValue("xls", File.ReadAllBytes("C:/aFolder/hello.xlsx"));
       update.ExecuteNonQuery();
  </code></pre>
  
  <p>It works, but <strong>I want to open it too</strong>!<br>
  How do I do that?
  Note, not read blob-data, but open the actual "hello.xlsx" file.</p>
  
  <p>I have tried the following:
  <a href="http://dotnetsoldier.blogspot.com/2007/07/how-to-retrieve-blob-object-in-winforms.html" rel="nofollow">http://dotnetsoldier.blogspot.com/2007/07/how-to-retrieve-blob-object-in-winforms.html</a>
  I can see it works, as "Binary.Length" is exactly the size of my "hello.xlsx" when executing - but the file doesn´t open, and that´s my problem.</p>
  
  <p>Please help me out!</p>
  
  <p>EDIT:
  HERE IS THE CODE THAT I CURRENTLY USE TO "OPEN" THE SPREADSHEET:</p>
  
  <pre><code>SqlConnection conn =
          new SqlConnection
             (global::MY_PROJECT.Properties.Settings.Default.DB_1ConnectionString);
  
       conn.Open();
  
       SqlCommand Cmd = new SqlCommand("select Attachment from Requests where RequestsID = 27", conn);
       Cmd.CommandType = CommandType.Text;
  
       SqlDataReader Reader = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
       //
       string DocumentName = null;
       FileStream FStream = null;
       BinaryWriter BWriter = null;
       //
       //
       //
       byte[] Binary = null;
       const int ChunkSize = 100;
       int SizeToWrite = 0;
       MemoryStream MStream = null;
       //
       while (Reader.Read())
       {
          DocumentName = Reader["Attachment"].ToString();
          // Create a file to hold the output.
          FStream = new FileStream(@"c:\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
          BWriter = new BinaryWriter(FStream);
          Binary = (Reader["Attachment"]) as byte[];
          SizeToWrite = ChunkSize;
          MStream = new MemoryStream(Binary);
          //
          for (int i = 0; i &lt; Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
          {
             if (i + ChunkSize &gt;= Binary.Length) SizeToWrite = Binary.Length - i;
             byte[] Chunk = new byte[SizeToWrite];
             MStream.Read(Chunk, 0, SizeToWrite);
             BWriter.Write(Chunk);
             BWriter.Flush();
          }
          BWriter.Close();
          FStream.Close();
       }
       FStream.Dispose();
  
       conn.Close();
  </code></pre>