title: How to get Image data from SQL Server, Write To File, Save File to Disk using C#
body: <p>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.</p>
  
  <p>I'm able to save the file to my local drive, but it appears to be corrupting the file in the process.</p>
  
  <p>What I'm trying to do:</p>
  
  <ol>
  <li>Retrieve binary data of type IMAGE from SQL Server Database.</li>
  <li>Create a file from the binary data.</li>
  <li>Save the file to a local directory.</li>
  </ol>
  
  <p>My CODE:</p>
  
  <pre><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;
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>Thanks in advance. </p>