C#, Export binary data to file from MS Sql Server Database Table


SqlConnection connection = new SqlConnection("server=x1;uid=x2;pwd=x3;database=x4;");
// Select binary data from db
SqlCommand command = new
  SqlCommand("select Filename, Attachment, Convert(nvarchar(5), ID) + ‘_’ + Filename as NewFilename   from MyAttachments", connection);
SqlDataReader sqlDr = command.ExecuteReader();
while (sqlDr.Read())
    string filename = sqlDr.GetString(0);
    byte[] attachment = (byte[])sqlDr.GetValue(1);
    string newFilename = sqlDr.GetString(2);
    FileStream fs = new FileStream(@"D:\B2F\" + newFilename, FileMode.Create);
    fs.Write(attachment, 0, attachment.Length);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s