title: Export blob from remote sql server and save to file on disk where sql server is located [C#]
body: <p>What i Need to do:
  im working on a backup and restore tool for my Company. Backup remote SQL databases is done without any Problems. But i have Problems while restoring them. I'm currently creating a temporary table on the remote SQL where the binary of the database is saved. </p>
  
  <p>Now i Need to Export this binary field from a remote SQL Server to a file that Needs to be saved on remote disk too. This tool has the requirement to get started on local machine so there is no way of running it on remote Server.</p>
  
  <p>Current code part:</p>
  
  <pre><code>using (SqlConnection conn = new SqlConnection(sqlConnectionString))
              {
                  System.Data.SqlClient.SqlCommand commandAdd = new SqlCommand("CREATE TABLE dbo.tempTable (filename char(50), blob image);", conn);
                  conn.Open();
  
                  if (commandAdd.ExecuteNonQuery() != 0)
                  {
                      byte[] fileBytes = System.IO.File.ReadAllBytes(fileSource);
                      System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("INSERT INTO dbo.tempTable (blob,filename) values (@blob,@name)", conn);
                      command.Parameters.AddWithValue("blob", fileBytes);
                      command.Parameters.AddWithValue("name", dbName);
  
                      if (command.ExecuteNonQuery() != 0)
                      {
                          // This is just for testing if i get binary back
                          // string SQL = "SELECT blob FROM dbo.tempTable";
                          // SqlCommand cmd = new SqlCommand(SQL, conn);
                          // byte[] byt = (byte[])cmd.ExecuteScalar();
  
                          // I think Problem is within this 2 lines..
                          Server server = new Server(new ServerConnection(conn));
                          server.ConnectionContext.ExecuteReader("'bcp.exe \"SELECT blob FROM dbo.tempTable\" queryout " + destinationSource + " -T -c'");
  
                          Restore restore = new Restore();
                          restore.Database = "_" + dbName;
                          restore.Action = RestoreActionType.Database;
                          restore.ReplaceDatabase = true;
                          restore.Devices.AddDevice(destinationSource, DeviceType.File);
                          restore.ReplaceDatabase = true;
                          restore.NoRecovery = false;
                          Server sqlServer = new Server(new ServerConnection(conn));
                          restore.SqlRestore(sqlServer);
                      }
                  }
  
                  SqlCommand commandDelete = new SqlCommand("DROP TABLE dbo.tempTable", conn);
                  commandDelete.ExecuteNonQuery();
                  conn.Close();
              }
  </code></pre>
  
  <p>Thanks</p>